From f6eb6b4fe844ae60044f2f47af26cae85f731cea Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Thu, 6 Apr 2023 08:32:24 +0200 Subject: [PATCH 001/170] EC66-PYTHON - Avoiding the use of quotation marks --- .../python/PythonRuleRepository.java | 8 ++--- .../python/checks/AvoidDoubleQuoteCheck.java | 31 +++++++++++++++++++ .../l10n/python/rules/python/EC66.html | 27 ++++++++++++++++ .../python/PythonRuleRepositoryTest.java | 4 +-- .../python/checks/AvoidDoubleQuoteTest.java | 11 +++++++ .../resources/checks/avoidDoubleQuoteCheck.py | 13 ++++++++ 6 files changed, 86 insertions(+), 8 deletions(-) create mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java create mode 100644 python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC66.html create mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteTest.java create mode 100644 python-plugin/src/test/resources/checks/avoidDoubleQuoteCheck.py diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java index 2a6f0225c..7183f872c 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java @@ -29,12 +29,7 @@ import java.util.List; import java.util.Map; -import fr.greencodeinitiative.python.checks.AvoidFullSQLRequest; -import fr.greencodeinitiative.python.checks.AvoidGettersAndSetters; -import fr.greencodeinitiative.python.checks.AvoidGlobalVariableInFunctionCheck; -import fr.greencodeinitiative.python.checks.AvoidSQLRequestInLoop; -import fr.greencodeinitiative.python.checks.AvoidTryCatchFinallyCheck; -import fr.greencodeinitiative.python.checks.NoFunctionCallWhenDeclaringForLoop; +import fr.greencodeinitiative.python.checks.*; import org.apache.commons.lang.StringUtils; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.api.server.rule.RulesDefinitionAnnotationLoader; @@ -87,6 +82,7 @@ public String repositoryKey() { @Override public List checkClasses() { return Arrays.asList( + AvoidDoubleQuoteCheck.class, AvoidGettersAndSetters.class, AvoidGlobalVariableInFunctionCheck.class, AvoidSQLRequestInLoop.class, diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java new file mode 100644 index 000000000..db3146318 --- /dev/null +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java @@ -0,0 +1,31 @@ +package fr.greencodeinitiative.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.SubscriptionContext; +import org.sonar.plugins.python.api.tree.StringLiteral; +import org.sonar.plugins.python.api.tree.Tree; + +@Rule( + key = AvoidDoubleQuoteCheck.RULE_KEY, + name = AvoidDoubleQuoteCheck.MESSAGE_RULE, + description = AvoidDoubleQuoteCheck.MESSAGE_RULE, + priority = Priority.MINOR, + tags = {"bug", "eco-design", "ecocode"}) +public class AvoidDoubleQuoteCheck extends PythonSubscriptionCheck { + public static final String RULE_KEY = "EC66"; + public static final String MESSAGE_RULE = "Avoid using quotation mark (\"), prefer using simple quote (')"; + @Override + public void initialize(Context context) { + context.registerSyntaxNodeConsumer(Tree.Kind.STRING_LITERAL, this::visitNodeString); + } + + private void visitNodeString(SubscriptionContext subscriptionContext) { + StringLiteral stringLiteral = (StringLiteral) subscriptionContext.syntaxNode(); + + if (!stringLiteral.stringElements().isEmpty() && stringLiteral.stringElements().get(0).value().startsWith("\"")){ + subscriptionContext.addIssue(stringLiteral, MESSAGE_RULE); + } + } +} diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC66.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC66.html new file mode 100644 index 000000000..0a94f3529 --- /dev/null +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC66.html @@ -0,0 +1,27 @@ +

+ The shape using the quotation marks (") allows the developer to insert variables that will be substituted at run time.
+ But if the string does not have a variable, use quotes (') instead.
+ Thus, language will not look for variables to substitute, which will reduce the consumption of CPU cycles. +

+

Noncompliant Code Example

+
+    # in variables
+    firstname = "Andrea" # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}}
+
+    # in functions
+    def my_function(name, age):
+        print(name + 'is' + age + ' yo.')
+
+    my_function("Robert", 12) # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}}
+
+

Compliant Solution

+
+    # in variables
+    firstname = 'Andrea'
+
+    # in functions
+    def my_function(name, age):
+        print(name + 'is' + age + ' yo.')
+
+    my_function('Robert', 12)
+
diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java index 101ff2841..f724dd805 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java @@ -44,8 +44,8 @@ public void init() { public void test() { assertThat(pythonRuleRepository.repositoryKey()).isEqualTo(PythonRuleRepository.REPOSITORY_KEY); assertThat(context.repositories()).hasSize(1).extracting("key").containsExactly(pythonRuleRepository.repositoryKey()); - assertThat(context.repositories().get(0).rules()).hasSize(6); - assertThat(pythonRuleRepository.checkClasses()).hasSize(6); + assertThat(context.repositories().get(0).rules()).hasSize(7); + assertThat(pythonRuleRepository.checkClasses()).hasSize(7); } diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteTest.java new file mode 100644 index 000000000..1079b1050 --- /dev/null +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteTest.java @@ -0,0 +1,11 @@ +package fr.greencodeinitiative.python.checks; + +import org.junit.Test; +import org.sonar.python.checks.utils.PythonCheckVerifier; + +public class AvoidDoubleQuoteTest { + @Test + public void test() { + PythonCheckVerifier.verify("src/test/resources/checks/avoidDoubleQuoteCheck.py", new AvoidDoubleQuoteCheck()); + } +} diff --git a/python-plugin/src/test/resources/checks/avoidDoubleQuoteCheck.py b/python-plugin/src/test/resources/checks/avoidDoubleQuoteCheck.py new file mode 100644 index 000000000..0af5f44ee --- /dev/null +++ b/python-plugin/src/test/resources/checks/avoidDoubleQuoteCheck.py @@ -0,0 +1,13 @@ +# in variables +firstname = "Andrea" # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}} +lastname = 'Doe' +cars = ["Renault", "Fiat", "Citroen"] # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}} {{Avoid using quotation mark ("), prefer using simple quote (')}} {{Avoid using quotation mark ("), prefer using simple quote (')}} +courses = ['mathematics', 'french', 'IT sciences'] +instruments = ['guitar', "bass", 'drums'] # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}} + +# in functions +def my_function(name, age): + print(name + 'is' + age + ' yo.') + +my_function("Robert", 12) # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}} +my_function('Robert', 12) \ No newline at end of file From 9849ce4ed3c48a6bdcecd967c4e3abef14650741 Mon Sep 17 00:00:00 2001 From: plougastela Date: Thu, 6 Apr 2023 09:50:08 +0200 Subject: [PATCH 002/170] CRJVM204 Detect unoptimized image format --- .../greencodeinitiative/java/RulesList.java | 23 +------- .../checks/DetectUnoptimizedImageFormat.java | 42 +++++++++++++ .../l10n/java/rules/java/CRJVM204.html | 15 +++++ .../l10n/java/rules/java/CRJVM204.json | 15 +++++ .../files/DetectUnoptimizedFileFormat.java | 59 +++++++++++++++++++ .../DetectUnoptimizedFileFormatComplient.java | 47 +++++++++++++++ .../DetectUnoptimizedImageFormatTest.java | 23 ++++++++ 7 files changed, 204 insertions(+), 20 deletions(-) create mode 100644 java-plugin/src/main/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormat.java create mode 100644 java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.html create mode 100644 java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.json create mode 100644 java-plugin/src/test/files/DetectUnoptimizedFileFormat.java create mode 100644 java-plugin/src/test/files/DetectUnoptimizedFileFormatComplient.java create mode 100644 java-plugin/src/test/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormatTest.java diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java index d6a5cdbf4..76d268c01 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java @@ -24,25 +24,7 @@ import java.util.Collections; import java.util.List; -import fr.greencodeinitiative.java.checks.ArrayCopyCheck; -import fr.greencodeinitiative.java.checks.AvoidConcatenateStringsInLoop; -import fr.greencodeinitiative.java.checks.AvoidFullSQLRequest; -import fr.greencodeinitiative.java.checks.AvoidGettingSizeCollectionInLoop; -import fr.greencodeinitiative.java.checks.AvoidMultipleIfElseStatement; -import fr.greencodeinitiative.java.checks.AvoidRegexPatternNotStatic; -import fr.greencodeinitiative.java.checks.AvoidSQLRequestInLoop; -import fr.greencodeinitiative.java.checks.AvoidSetConstantInBatchUpdate; -import fr.greencodeinitiative.java.checks.AvoidSpringRepositoryCallInLoopCheck; -import fr.greencodeinitiative.java.checks.AvoidStatementForDMLQueries; -import fr.greencodeinitiative.java.checks.AvoidUsageOfStaticCollections; -import fr.greencodeinitiative.java.checks.AvoidUsingGlobalVariablesCheck; -import fr.greencodeinitiative.java.checks.FreeResourcesOfAutoCloseableInterface; -import fr.greencodeinitiative.java.checks.IncrementCheck; -import fr.greencodeinitiative.java.checks.InitializeBufferWithAppropriateSize; -import fr.greencodeinitiative.java.checks.NoFunctionCallWhenDeclaringForLoop; -import fr.greencodeinitiative.java.checks.OptimizeReadFileExceptions; -import fr.greencodeinitiative.java.checks.UnnecessarilyAssignValuesToVariables; -import fr.greencodeinitiative.java.checks.UseCorrectForLoop; +import fr.greencodeinitiative.java.checks.*; import org.sonar.plugins.java.api.JavaCheck; public final class RulesList { @@ -77,7 +59,8 @@ public static List> getJavaChecks() { AvoidUsingGlobalVariablesCheck.class, AvoidSetConstantInBatchUpdate.class, FreeResourcesOfAutoCloseableInterface.class, - AvoidMultipleIfElseStatement.class + AvoidMultipleIfElseStatement.class, + DetectUnoptimizedImageFormat.class )); } diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormat.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormat.java new file mode 100644 index 000000000..43eb24d70 --- /dev/null +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormat.java @@ -0,0 +1,42 @@ +package fr.greencodeinitiative.java.checks; + +import org.sonar.check.Priority; +import org.sonar.check.Rule; +import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; +import org.sonar.plugins.java.api.tree.LiteralTree; +import org.sonar.plugins.java.api.tree.Tree; + +import java.util.Arrays; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Rule( + key = "CRJVM204", + name = "Developpement", + description = IncrementCheck.MESSAGERULE, + priority = Priority.MINOR, + tags = {"bug"}) +public class DetectUnoptimizedImageFormat extends IssuableSubscriptionVisitor { + + protected static final String MESSAGERULE = "Detect unoptimized image format"; + protected static final String MESSAGEERROR = "If possible, utilisation of svg image format is recommended over other image format."; + protected static Pattern IMG_EXTENSION = Pattern.compile("\\.(bmp|ico|tiff|webp|png|jpg|jpeg|jfif|pjpeg|pjp|gif|avif|apng)"); + + @Override + public List nodesToVisit() { + return Arrays.asList(Tree.Kind.STRING_LITERAL, Tree.Kind.TEXT_BLOCK); + } + + @Override + public void visitNode(Tree tree) { + + if (tree.is(Tree.Kind.STRING_LITERAL, Tree.Kind.TEXT_BLOCK)) { + final String strValue = ((LiteralTree) tree).value(); + final Matcher matcher = IMG_EXTENSION.matcher(strValue); + if(matcher.find()) { + reportIssue(tree, MESSAGEERROR); + } + } + } +} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.html b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.html new file mode 100644 index 000000000..f2096cf9d --- /dev/null +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.html @@ -0,0 +1,15 @@ +

"If possible, utilisation of svg image format is recommended over other image format.

+

Noncompliant Code Example

+
+    jEditorPane.setContentType("text/html");
+    jEditorPane.setText("\"Grapefruit\"");
+
+

Compliant Solution

+
+    jEditorPane.setContentType("text/html");
+    jEditorPane.setText("\"Grapefruit\"");
+
diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.json new file mode 100644 index 000000000..199e43d9c --- /dev/null +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.json @@ -0,0 +1,15 @@ +{ + "title": "Detect unoptimized image format", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "15min" + }, + "tags": [ + "eco-design", + "bug", + "ecocode" + ], + "defaultSeverity": "Minor" +} diff --git a/java-plugin/src/test/files/DetectUnoptimizedFileFormat.java b/java-plugin/src/test/files/DetectUnoptimizedFileFormat.java new file mode 100644 index 000000000..31ad318a8 --- /dev/null +++ b/java-plugin/src/test/files/DetectUnoptimizedFileFormat.java @@ -0,0 +1,59 @@ +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.LayoutManager; +import java.io.IOException; +import java.net.URL; + +import javax.swing.JEditorPane; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +public class SwingTester { + private static void createWindow() { + JFrame frame = new JFrame("Swing Tester"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + createUI(frame); + frame.setSize(560, 450); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private static void createUI(final JFrame frame) { + JPanel panel = new JPanel(); + LayoutManager layout = new FlowLayout(); + panel.setLayout(layout); + + JEditorPane jEditorPane = new JEditorPane(); + jEditorPane.setEditable(false); + + jEditorPane.setContentType("text/html"); + jEditorPane.setText("Le titre avec une partie en gras," + + " et une autre partie en bleu." + + " \"Grapefruit" + + " \"Grapefruit" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.bmp\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.tiff\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.webp\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.png\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.jpeg\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.jfif\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.pjpeg\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.pjp\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.gif\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.avif\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.apng\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} + ""); + + JScrollPane jScrollPane = new JScrollPane(jEditorPane); + jScrollPane.setPreferredSize(new Dimension(540, 400)); + + panel.add(jScrollPane); + panel.add(jScrollPane2); + frame.getContentPane().add(panel, BorderLayout.CENTER); + } +} \ No newline at end of file diff --git a/java-plugin/src/test/files/DetectUnoptimizedFileFormatComplient.java b/java-plugin/src/test/files/DetectUnoptimizedFileFormatComplient.java new file mode 100644 index 000000000..abd142116 --- /dev/null +++ b/java-plugin/src/test/files/DetectUnoptimizedFileFormatComplient.java @@ -0,0 +1,47 @@ +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.LayoutManager; +import java.io.IOException; +import java.net.URL; + +import javax.swing.JEditorPane; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +public class SwingTester { + private static void createWindow() { + JFrame frame = new JFrame("Swing Tester"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + createUI(frame); + frame.setSize(560, 450); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private static void createUI(final JFrame frame){ + JPanel panel = new JPanel(); + LayoutManager layout = new FlowLayout(); + panel.setLayout(layout); + + JEditorPane jEditorPane3 = new JEditorPane(); + jEditorPane3.setEditable(false); + + jEditorPane3.setContentType("text/html"); + jEditorPane3.setText("Le titre avec une partie en gras," + + " et une autre partie en bleu." + + " \"Grapefruit" + + ""); + + JScrollPane jScrollPane = new JScrollPane(jEditorPane); + jScrollPane.setPreferredSize(new Dimension(540,400)); + + panel.add(jScrollPane); + panel.add(jScrollPane2); + panel.add(jScrollPane3); + frame.getContentPane().add(panel, BorderLayout.CENTER); + } +} \ No newline at end of file diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormatTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormatTest.java new file mode 100644 index 000000000..80f357786 --- /dev/null +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormatTest.java @@ -0,0 +1,23 @@ +package fr.greencodeinitiative.java.checks; + +import org.junit.jupiter.api.Test; +import org.sonar.java.checks.verifier.CheckVerifier; + +public class DetectUnoptimizedImageFormatTest { + + @Test + void test() { + CheckVerifier.newVerifier() + .onFile("src/test/files/DetectUnoptimizedImageFormat.java") + .withCheck(new DetectUnoptimizedImageFormat()) + .verifyIssues(); + } + + @Test + void testComplient() { + CheckVerifier.newVerifier() + .onFile("src/test/files/DetectUnoptimizedFileFormatComplient.java") + .withCheck(new DetectUnoptimizedImageFormat()) + .verifyNoIssues(); + } +} From 5ec73df950171888c1063ccdfb17525e32c3174b Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Thu, 6 Apr 2023 10:19:13 +0200 Subject: [PATCH 003/170] EC66-PYTHON - up imports --- .../greencodeinitiative/python/PythonRuleRepository.java | 8 +++++++- .../src/test/resources/checks/avoidDoubleQuoteCheck.py | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java index 7183f872c..b9056b13a 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java @@ -29,7 +29,13 @@ import java.util.List; import java.util.Map; -import fr.greencodeinitiative.python.checks.*; +import fr.greencodeinitiative.python.checks.AvoidDoubleQuoteCheck; +import fr.greencodeinitiative.python.checks.AvoidFullSQLRequest; +import fr.greencodeinitiative.python.checks.AvoidGettersAndSetters; +import fr.greencodeinitiative.python.checks.AvoidGlobalVariableInFunctionCheck; +import fr.greencodeinitiative.python.checks.AvoidSQLRequestInLoop; +import fr.greencodeinitiative.python.checks.AvoidTryCatchFinallyCheck; +import fr.greencodeinitiative.python.checks.NoFunctionCallWhenDeclaringForLoop; import org.apache.commons.lang.StringUtils; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.api.server.rule.RulesDefinitionAnnotationLoader; diff --git a/python-plugin/src/test/resources/checks/avoidDoubleQuoteCheck.py b/python-plugin/src/test/resources/checks/avoidDoubleQuoteCheck.py index 0af5f44ee..893f24e8e 100644 --- a/python-plugin/src/test/resources/checks/avoidDoubleQuoteCheck.py +++ b/python-plugin/src/test/resources/checks/avoidDoubleQuoteCheck.py @@ -10,4 +10,4 @@ def my_function(name, age): print(name + 'is' + age + ' yo.') my_function("Robert", 12) # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}} -my_function('Robert', 12) \ No newline at end of file +my_function('Robert', 12) From a2fbf1b674159dffd31f51f03e9fff135cab678e Mon Sep 17 00:00:00 2001 From: plougastela Date: Thu, 6 Apr 2023 11:03:33 +0200 Subject: [PATCH 004/170] CRJVM204 Detect unoptimized image format --- .../java/checks/DetectUnoptimizedImageFormat.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormat.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormat.java index 43eb24d70..2b3190b19 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormat.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormat.java @@ -20,7 +20,7 @@ public class DetectUnoptimizedImageFormat extends IssuableSubscriptionVisitor { protected static final String MESSAGERULE = "Detect unoptimized image format"; - protected static final String MESSAGEERROR = "If possible, utilisation of svg image format is recommended over other image format."; + protected static final String MESSAGEERROR = "If possible, the utilisation of svg image format (or html tag) is recommended over other image format."; protected static Pattern IMG_EXTENSION = Pattern.compile("\\.(bmp|ico|tiff|webp|png|jpg|jpeg|jfif|pjpeg|pjp|gif|avif|apng)"); @Override From cc526cc44e5face12f63042f1369d6647d1db420 Mon Sep 17 00:00:00 2001 From: plougastela Date: Thu, 6 Apr 2023 11:19:10 +0200 Subject: [PATCH 005/170] CRJVM204 Detect unoptimized image format --- .../files/DetectUnoptimizedFileFormat.java | 59 ------------- .../files/DetectUnoptimizedImageFormat.java | 84 +++++++++++++++++++ ...etectUnoptimizedImageFormatComplient.java} | 36 ++++++-- .../DetectUnoptimizedImageFormatTest.java | 2 +- 4 files changed, 114 insertions(+), 67 deletions(-) delete mode 100644 java-plugin/src/test/files/DetectUnoptimizedFileFormat.java create mode 100644 java-plugin/src/test/files/DetectUnoptimizedImageFormat.java rename java-plugin/src/test/files/{DetectUnoptimizedFileFormatComplient.java => DetectUnoptimizedImageFormatComplient.java} (50%) diff --git a/java-plugin/src/test/files/DetectUnoptimizedFileFormat.java b/java-plugin/src/test/files/DetectUnoptimizedFileFormat.java deleted file mode 100644 index 31ad318a8..000000000 --- a/java-plugin/src/test/files/DetectUnoptimizedFileFormat.java +++ /dev/null @@ -1,59 +0,0 @@ -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.LayoutManager; -import java.io.IOException; -import java.net.URL; - -import javax.swing.JEditorPane; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - -public class SwingTester { - private static void createWindow() { - JFrame frame = new JFrame("Swing Tester"); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - createUI(frame); - frame.setSize(560, 450); - frame.setLocationRelativeTo(null); - frame.setVisible(true); - } - - private static void createUI(final JFrame frame) { - JPanel panel = new JPanel(); - LayoutManager layout = new FlowLayout(); - panel.setLayout(layout); - - JEditorPane jEditorPane = new JEditorPane(); - jEditorPane.setEditable(false); - - jEditorPane.setContentType("text/html"); - jEditorPane.setText("Le titre avec une partie en gras," + - " et une autre partie en bleu." + - " \"Grapefruit" + - " \"Grapefruit" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.bmp\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.tiff\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.webp\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.png\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.jpeg\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.jfif\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.pjpeg\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.pjp\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.gif\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.avif\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.apng\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, utilisation of svg image format is recommended over other image format.}} - ""); - - JScrollPane jScrollPane = new JScrollPane(jEditorPane); - jScrollPane.setPreferredSize(new Dimension(540, 400)); - - panel.add(jScrollPane); - panel.add(jScrollPane2); - frame.getContentPane().add(panel, BorderLayout.CENTER); - } -} \ No newline at end of file diff --git a/java-plugin/src/test/files/DetectUnoptimizedImageFormat.java b/java-plugin/src/test/files/DetectUnoptimizedImageFormat.java new file mode 100644 index 000000000..c8c631820 --- /dev/null +++ b/java-plugin/src/test/files/DetectUnoptimizedImageFormat.java @@ -0,0 +1,84 @@ +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.LayoutManager; +import java.io.IOException; +import java.net.URL; + +import javax.swing.JEditorPane; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +public class DetectUnoptimizedImageFormat { + + private String img_bmp = "test/image.bmp"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + private String img_ico = "image.ico"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + private String img_tiff = "test/path/to/image.tiff"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + private String img_webp = "test/path/to/" + "image.webp"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + private String img_jpg = "image.jpg"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + private String img_jpeg = "image.jpeg"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + private String img_jfif = "image.jfif"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + private String img_pjpeg = "image.pjpeg"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + private String img_pjp = "image.pjp"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + private String img_gif = "image.gif"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + private String img_avif = "image.avif"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + private String img_apng = "image.apng"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + + private static String getImagePath(String image) { + return "path/to/" + image; + } + + private static void testImage() { + String img1 = getImagePath("test/image.bmp"); // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + String img2 = getImagePath("image.ico"); // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + String img3 = getImagePath("image.jpg"); // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + } + + private static void createWindow() { + JFrame frame = new JFrame("Swing Tester"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + createUI(frame); + frame.setSize(560, 450); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private static void createUI(final JFrame frame) { + JPanel panel = new JPanel(); + LayoutManager layout = new FlowLayout(); + panel.setLayout(layout); + + JEditorPane jEditorPane = new JEditorPane(); + jEditorPane.setEditable(false); + + jEditorPane.setContentType("text/html"); + jEditorPane.setText("Le titre avec une partie en gras," + + " et une autre partie en bleu." + + " html tag) is recommended over other image format.}} + " alt=\"Grapefruit slice atop a pile of other slices\">" + + " \"Grapefruit" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.bmp\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.tiff\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.webp\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.png\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.jpeg\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.jfif\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.pjpeg\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.pjp\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.gif\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.avif\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + " src=\"/media/cc0-images/grapefruit-slice-332-332.apng\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + ""); + + JScrollPane jScrollPane = new JScrollPane(jEditorPane); + jScrollPane.setPreferredSize(new Dimension(540, 400)); + + panel.add(jScrollPane); + panel.add(jScrollPane2); + frame.getContentPane().add(panel, BorderLayout.CENTER); + } +} \ No newline at end of file diff --git a/java-plugin/src/test/files/DetectUnoptimizedFileFormatComplient.java b/java-plugin/src/test/files/DetectUnoptimizedImageFormatComplient.java similarity index 50% rename from java-plugin/src/test/files/DetectUnoptimizedFileFormatComplient.java rename to java-plugin/src/test/files/DetectUnoptimizedImageFormatComplient.java index abd142116..c0ce54011 100644 --- a/java-plugin/src/test/files/DetectUnoptimizedFileFormatComplient.java +++ b/java-plugin/src/test/files/DetectUnoptimizedImageFormatComplient.java @@ -10,7 +10,19 @@ import javax.swing.JPanel; import javax.swing.JScrollPane; -public class SwingTester { +public class DetectUnoptimizedImageFormat { + + private String img_svg = "test/image.svg"; // Complient + + private String getImagePath(String image) { + return "path/to/" + image; + } + + private static void testImage() { + String img1 = getImagePath("test/image.svg"); // Complient + String img2 = getImagePath("image.svg"); // Complient + } + private static void createWindow() { JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); @@ -20,24 +32,34 @@ private static void createWindow() { frame.setVisible(true); } - private static void createUI(final JFrame frame){ + private static void createUI(final JFrame frame) { JPanel panel = new JPanel(); LayoutManager layout = new FlowLayout(); panel.setLayout(layout); - JEditorPane jEditorPane3 = new JEditorPane(); - jEditorPane3.setEditable(false); + JEditorPane jEditorPane = new JEditorPane(); + jEditorPane.setEditable(false); - jEditorPane3.setContentType("text/html"); - jEditorPane3.setText("Le titre avec une partie en gras," + + jEditorPane.setContentType("text/html"); + jEditorPane.setText("Le titre avec une partie en gras," + " et une autre partie en bleu." + " \"Grapefruit" + ""); + JEditorPane jEditorPane1 = new JEditorPane(); + jEditorPane1.setEditable(false); + + jEditorPane1.setContentType("text/html"); + jEditorPane1.setText("Le titre avec une partie en gras," + + " et une autre partie en bleu." + + " " + // Complient + " " + + ""); + JScrollPane jScrollPane = new JScrollPane(jEditorPane); - jScrollPane.setPreferredSize(new Dimension(540,400)); + jScrollPane.setPreferredSize(new Dimension(540, 400)); panel.add(jScrollPane); panel.add(jScrollPane2); diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormatTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormatTest.java index 80f357786..d2bd21858 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormatTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormatTest.java @@ -16,7 +16,7 @@ void test() { @Test void testComplient() { CheckVerifier.newVerifier() - .onFile("src/test/files/DetectUnoptimizedFileFormatComplient.java") + .onFile("src/test/files/DetectUnoptimizedImageFormatComplient.java") .withCheck(new DetectUnoptimizedImageFormat()) .verifyNoIssues(); } From 7f427d0b831898d5438fbffb9da50070d015edfe Mon Sep 17 00:00:00 2001 From: plougastela Date: Thu, 6 Apr 2023 11:20:22 +0200 Subject: [PATCH 006/170] CRPYT203 - Detect unoptimized image format --- .../checks/DetectUnoptimizedImageFormat.java | 35 ++++++++++++++++++ .../l10n/python/rules/python/CRPYT203.html | 20 +++++++++++ .../DetectUnoptimizedImageFormatTest.java | 13 +++++++ .../checks/detectUnoptimizedImageFormat.py | 36 +++++++++++++++++++ .../detectUnoptimizedImageFormatComplient.py | 17 +++++++++ 5 files changed, 121 insertions(+) create mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java create mode 100644 python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/CRPYT203.html create mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java create mode 100644 python-plugin/src/test/resources/checks/detectUnoptimizedImageFormat.py create mode 100644 python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatComplient.py diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java new file mode 100644 index 000000000..8db89d276 --- /dev/null +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java @@ -0,0 +1,35 @@ +package fr.greencodeinitiative.python.checks; + +import com.sun.source.tree.LiteralTree; +import org.sonar.plugins.python.api.PythonSubscriptionCheck; +import org.sonar.plugins.python.api.SubscriptionContext; +import org.sonar.plugins.python.api.tree.StringLiteral; +import org.sonar.plugins.python.api.tree.Tree; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class DetectUnoptimizedImageFormat extends PythonSubscriptionCheck { + + public static final String RULE_KEY = "CRPYT203"; + + protected static final String MESSAGERULE = "Detect unoptimized image format"; + protected static final String MESSAGEERROR = "If possible, the utilisation of svg image format (or html tag) is recommended over other image format."; + protected static Pattern IMG_EXTENSION = Pattern.compile("\\.(bmp|ico|tiff|webp|png|jpg|jpeg|jfif|pjpeg|pjp|gif|avif|apng)"); + + @Override + public void initialize(Context context) { + context.registerSyntaxNodeConsumer(Tree.Kind.STRING_LITERAL, this::visitNodeString); + } + + public void visitNodeString(SubscriptionContext ctx) { + if (ctx.syntaxNode().is(Tree.Kind.STRING_LITERAL)) { + final StringLiteral stringLiteral = (StringLiteral) ctx.syntaxNode(); + final String strValue = stringLiteral.trimmedQuotesValue(); + final Matcher matcher = IMG_EXTENSION.matcher(strValue); + if(matcher.find()) { + ctx.addIssue(stringLiteral, MESSAGEERROR); + } + } + } +} diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/CRPYT203.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/CRPYT203.html new file mode 100644 index 000000000..b7ca91bdf --- /dev/null +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/CRPYT203.html @@ -0,0 +1,20 @@ +

If possible, the utilisation of svg image format (or html tag) is recommended over other image format.

+

Noncompliant Code Example

+
+    public void foo() {
+        ...
+        img_jpg = "image.jpg"
+        ...
+    }
+
+
+

Compliant Solution

+
+
+    public void foo() {
+        ...
+        img_svg = "image.svg"
+        ...
+   }
+
+
diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java new file mode 100644 index 000000000..a65679236 --- /dev/null +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java @@ -0,0 +1,13 @@ +package fr.greencodeinitiative.python.checks; + +import org.junit.Test; +import org.sonar.python.checks.utils.PythonCheckVerifier; + +public class DetectUnoptimizedImageFormatTest { + + @Test + public void test() { + PythonCheckVerifier.verify("src/test/resources/checks/detectUnoptimizedImageFormat.py", new DetectUnoptimizedImageFormat()); + PythonCheckVerifier.verifyNoIssue("src/test/resources/checks/detectUnoptimizedImageFormatComplient.py", new DetectUnoptimizedImageFormat()); + } +} diff --git a/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormat.py b/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormat.py new file mode 100644 index 000000000..33e2145e9 --- /dev/null +++ b/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormat.py @@ -0,0 +1,36 @@ + +def testImage(image) : + return "path/to/" + image + + +def testImageFormat2() : + + img_bmp = "test/image.bmp" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + img_ico = "image.ico" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + img_tiff = "test/path/to/image.tiff" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + img_webp = "test/path/to/" + "image.webp" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + img_jpg = "image.jpg" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + img_jpeg = "image.jpeg" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + img_jfif = "image.jfif" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + img_pjpeg = "image.pjpeg" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + img_pjp = "image.pjp" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + img_gif = "image.gif" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + img_avif = "image.avif" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + img_apng = "image.apng" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + image_format = testImage("image.jpg") # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + return ('' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + + '' ) \ No newline at end of file diff --git a/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatComplient.py b/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatComplient.py new file mode 100644 index 000000000..d05486a16 --- /dev/null +++ b/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatComplient.py @@ -0,0 +1,17 @@ + +def testImage(image) : + return "path/to/" + image + + +def testImageFormat2() : + + img_svg = "test/image.svg" # Complient + + image_format = testImage("image.svg") # Complient + + image_svg_html = ('' + # Complient + '' + + '') + + return ('' # Complient + + '' ) \ No newline at end of file From 3ebdf119a02c7caa44c033dc0792459e3707343f Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Thu, 6 Apr 2023 11:43:33 +0200 Subject: [PATCH 007/170] feat: add rules for avoirding list comprehensions in for-loops declaration --- .../python/PythonRuleRepository.java | 10 +-- .../AvoidListComprehensionInIterations.java | 67 +++++++++++++++++++ .../l10n/python/rules/python/EC404.html | 13 ++++ ...voidListComprehensionInIterationsTest.java | 11 +++ .../AvoidListComprehensionInIterations.py | 39 +++++++++++ 5 files changed, 133 insertions(+), 7 deletions(-) create mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java create mode 100644 python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC404.html create mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterationsTest.java create mode 100644 python-plugin/src/test/resources/checks/AvoidListComprehensionInIterations.py diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java index 2a6f0225c..8b073795f 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java @@ -29,12 +29,7 @@ import java.util.List; import java.util.Map; -import fr.greencodeinitiative.python.checks.AvoidFullSQLRequest; -import fr.greencodeinitiative.python.checks.AvoidGettersAndSetters; -import fr.greencodeinitiative.python.checks.AvoidGlobalVariableInFunctionCheck; -import fr.greencodeinitiative.python.checks.AvoidSQLRequestInLoop; -import fr.greencodeinitiative.python.checks.AvoidTryCatchFinallyCheck; -import fr.greencodeinitiative.python.checks.NoFunctionCallWhenDeclaringForLoop; +import fr.greencodeinitiative.python.checks.*; import org.apache.commons.lang.StringUtils; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.api.server.rule.RulesDefinitionAnnotationLoader; @@ -92,7 +87,8 @@ public List checkClasses() { AvoidSQLRequestInLoop.class, AvoidTryCatchFinallyCheck.class, NoFunctionCallWhenDeclaringForLoop.class, - AvoidFullSQLRequest.class + AvoidFullSQLRequest.class, + AvoidListComprehensionInIterations.class ); } diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java new file mode 100644 index 000000000..bc8ea7cec --- /dev/null +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java @@ -0,0 +1,67 @@ +package fr.greencodeinitiative.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.SubscriptionContext; +import org.sonar.plugins.python.api.tree.*; + +import static org.sonar.plugins.python.api.tree.Tree.Kind.*; + +@Rule( + key = AvoidListComprehensionInIterations.RULE_KEY, + name = AvoidListComprehensionInIterations.DESCRIPTION, + description = AvoidListComprehensionInIterations.DESCRIPTION, + priority = Priority.MINOR, + tags = {"bug", "eco-design", "ecocode"}) +public class AvoidListComprehensionInIterations extends PythonSubscriptionCheck { + + public static final String RULE_KEY = "EC404"; + public static final String DESCRIPTION = "Use generator comprehension instead of list comprehension in for loop declaration"; + + @Override + public void initialize(Context context) { + context.registerSyntaxNodeConsumer(FOR_STMT, this::visitIteration); + + } + + private void visitIteration(SubscriptionContext context) { + ForStatement forStatement = (ForStatement) context.syntaxNode(); + + Expression forTestExpression = forStatement.testExpressions().get(0); + if (forTestExpression.is(LIST_COMPREHENSION)) { + + context.addIssue(forTestExpression.firstToken(), DESCRIPTION); + + } else if (forTestExpression.is(CALL_EXPR)) { + CallExpression callExpression = (CallExpression) forTestExpression; + switch (callExpression.callee().firstToken().value()) { + case "zip": + case "filter": + case "enumerate": + callExpression.argumentList(). + arguments().forEach(e -> visitFunctionArguments(context, e.children().get(0))); + } + } + } + + private void visitFunctionArguments(SubscriptionContext context, Tree argument) { + if (argument.is(LIST_COMPREHENSION)) { + context.addIssue(argument.firstToken(), DESCRIPTION); + + } else if (argument.is(CALL_EXPR)) { + CallExpression callExpression = (CallExpression) argument; + switch (callExpression.callee().firstToken().value()) { + case "zip": + case "filter": + case "enumerate": + callExpression.argumentList(). + arguments().forEach(e -> visitFunctionArguments(context, e.children().get(0))); + break; + + } + } + + } + +} diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC404.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC404.html new file mode 100644 index 000000000..0e48db385 --- /dev/null +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC404.html @@ -0,0 +1,13 @@ +

Use generator comprehension instead of list comprehension in for loop declaration.

+

Python generators resemble lazy lists from other programming languages: when iterated over, they compute their values on the fly. They lack some list behaviors (indexing, len method, ...) but are memory-efficient, as they do not store each of their values in memory, unlike lists. Thus, when declared in a for-loop declaration, list comprehensions can be safely replaced with generator comprehensions.

+

For more details on list comprehensions vs generator comprehensions, see Python documentation.

+

Noncompliant Code Example

+
+for var in [for var2 in range(100)]:
+    ...
+
+

Compliant Solution

+
+for var in (for var2 in range(100)):
+    ...
+
diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterationsTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterationsTest.java new file mode 100644 index 000000000..8e722c25b --- /dev/null +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterationsTest.java @@ -0,0 +1,11 @@ +package fr.greencodeinitiative.python.checks; + +import org.junit.Test; +import org.sonar.python.checks.utils.PythonCheckVerifier; + +public class AvoidListComprehensionInIterationsTest { + @Test + public void test() { + PythonCheckVerifier.verify("src/test/resources/checks/AvoidListComprehensionInIterations.py", new AvoidListComprehensionInIterations()); + } +} diff --git a/python-plugin/src/test/resources/checks/AvoidListComprehensionInIterations.py b/python-plugin/src/test/resources/checks/AvoidListComprehensionInIterations.py new file mode 100644 index 000000000..9dab94c8b --- /dev/null +++ b/python-plugin/src/test/resources/checks/AvoidListComprehensionInIterations.py @@ -0,0 +1,39 @@ +def non_compliant_example_basic(): + for var in [var2 for var2 in range(1000)]: # Noncompliant {{Use generator comprehension instead of list comprehension in for loop declaration}} + print(var) + +def non_compliant_example_enumerate(): + for idx, var in enumerate([var2 for var2 in range(1000)]): # Noncompliant {{Use generator comprehension instead of list comprehension in for loop declaration}} + print(var) + +def non_compliant_example_zip(): + for var, var_ in zip([var2 for var2 in range(1000)], [var2 for var2 in range(1000)]): # Noncompliant {{Use generator comprehension instead of list comprehension in for loop declaration}} {{Use generator comprehension instead of list comprehension in for loop declaration}} + print(var) + +def non_compliant_example_zip(): + for var, var_ in zip([var2 for var2 in range(1000)], [var2 for var2 in range(1000)]): # Noncompliant {{Use generator comprehension instead of list comprehension in for loop declaration}} {{Use generator comprehension instead of list comprehension in for loop declaration}} + print(var) + +def non_compliant_example_enumerate_zip(): + for packed_var in enumerate(zip([1, 2, 3], filter(bool, [idx % 2 for idx in range(100)]))): # Noncompliant {{Use generator comprehension instead of list comprehension in for loop declaration}} + print(packed_var) + +def compliant_example_basic_1(): + for var in range(10): + print(var) + +def compliant_example_basic_2(): + for var in (var2 for var2 in range(1000)): + print(var) + +def compliant_example_with_filter(): + for var in filter(lambda x: x > 2, range(100)): + print(var) + +def compliant_example_with_enumerate(): + for idx, var in enumerate(range(1000)): + print(var) + +def compliant_example_with_zip(): + for var, var2 in zip((idx for idx in range(3)), ["a", "b", "c"]): + print(var) \ No newline at end of file From ee2be6c03f73c1e0d956389c124da5b658002305 Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Thu, 6 Apr 2023 12:27:23 +0200 Subject: [PATCH 008/170] fix: update number of rules in PythonRulesRepositoryTest --- .../greencodeinitiative/python/PythonRuleRepositoryTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java index 101ff2841..f724dd805 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java @@ -44,8 +44,8 @@ public void init() { public void test() { assertThat(pythonRuleRepository.repositoryKey()).isEqualTo(PythonRuleRepository.REPOSITORY_KEY); assertThat(context.repositories()).hasSize(1).extracting("key").containsExactly(pythonRuleRepository.repositoryKey()); - assertThat(context.repositories().get(0).rules()).hasSize(6); - assertThat(pythonRuleRepository.checkClasses()).hasSize(6); + assertThat(context.repositories().get(0).rules()).hasSize(7); + assertThat(pythonRuleRepository.checkClasses()).hasSize(7); } From a13b1c1bd4ad7a10544284182ceae6d9ed3d6bfe Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Thu, 6 Apr 2023 13:02:21 +0200 Subject: [PATCH 009/170] fix: add requireNonNull for agumentList to fix quality gate --- .../python/checks/AvoidListComprehensionInIterations.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java index bc8ea7cec..dec37acaa 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java @@ -6,6 +6,8 @@ import org.sonar.plugins.python.api.SubscriptionContext; import org.sonar.plugins.python.api.tree.*; +import java.util.Objects; + import static org.sonar.plugins.python.api.tree.Tree.Kind.*; @Rule( @@ -39,7 +41,7 @@ private void visitIteration(SubscriptionContext context) { case "zip": case "filter": case "enumerate": - callExpression.argumentList(). + Objects.requireNonNull(callExpression.argumentList()). arguments().forEach(e -> visitFunctionArguments(context, e.children().get(0))); } } @@ -55,7 +57,7 @@ private void visitFunctionArguments(SubscriptionContext context, Tree argument) case "zip": case "filter": case "enumerate": - callExpression.argumentList(). + Objects.requireNonNull(callExpression.argumentList()). arguments().forEach(e -> visitFunctionArguments(context, e.children().get(0))); break; From 0e947030aba278f2831699eb3a65b2b85393843e Mon Sep 17 00:00:00 2001 From: plougastela Date: Thu, 6 Apr 2023 13:03:41 +0200 Subject: [PATCH 010/170] CRPYT203 - Detect unoptimized image format --- .../greencodeinitiative/java/RulesList.java | 3 +- .../checks/DetectUnoptimizedImageFormat.java | 42 ---------- .../l10n/java/rules/java/CRJVM204.html | 15 ---- .../l10n/java/rules/java/CRJVM204.json | 15 ---- .../files/DetectUnoptimizedImageFormat.java | 84 ------------------- ...DetectUnoptimizedImageFormatComplient.java | 69 --------------- .../DetectUnoptimizedImageFormatTest.java | 23 ----- .../l10n/python/rules/python/CRPYT203.html | 38 +++++++-- 8 files changed, 33 insertions(+), 256 deletions(-) delete mode 100644 java-plugin/src/main/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormat.java delete mode 100644 java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.html delete mode 100644 java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.json delete mode 100644 java-plugin/src/test/files/DetectUnoptimizedImageFormat.java delete mode 100644 java-plugin/src/test/files/DetectUnoptimizedImageFormatComplient.java delete mode 100644 java-plugin/src/test/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormatTest.java diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java index 76d268c01..8f2a47c47 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java @@ -59,8 +59,7 @@ public static List> getJavaChecks() { AvoidUsingGlobalVariablesCheck.class, AvoidSetConstantInBatchUpdate.class, FreeResourcesOfAutoCloseableInterface.class, - AvoidMultipleIfElseStatement.class, - DetectUnoptimizedImageFormat.class + AvoidMultipleIfElseStatement.class )); } diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormat.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormat.java deleted file mode 100644 index 2b3190b19..000000000 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormat.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.greencodeinitiative.java.checks; - -import org.sonar.check.Priority; -import org.sonar.check.Rule; -import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; -import org.sonar.plugins.java.api.tree.LiteralTree; -import org.sonar.plugins.java.api.tree.Tree; - -import java.util.Arrays; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -@Rule( - key = "CRJVM204", - name = "Developpement", - description = IncrementCheck.MESSAGERULE, - priority = Priority.MINOR, - tags = {"bug"}) -public class DetectUnoptimizedImageFormat extends IssuableSubscriptionVisitor { - - protected static final String MESSAGERULE = "Detect unoptimized image format"; - protected static final String MESSAGEERROR = "If possible, the utilisation of svg image format (or html tag) is recommended over other image format."; - protected static Pattern IMG_EXTENSION = Pattern.compile("\\.(bmp|ico|tiff|webp|png|jpg|jpeg|jfif|pjpeg|pjp|gif|avif|apng)"); - - @Override - public List nodesToVisit() { - return Arrays.asList(Tree.Kind.STRING_LITERAL, Tree.Kind.TEXT_BLOCK); - } - - @Override - public void visitNode(Tree tree) { - - if (tree.is(Tree.Kind.STRING_LITERAL, Tree.Kind.TEXT_BLOCK)) { - final String strValue = ((LiteralTree) tree).value(); - final Matcher matcher = IMG_EXTENSION.matcher(strValue); - if(matcher.find()) { - reportIssue(tree, MESSAGEERROR); - } - } - } -} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.html b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.html deleted file mode 100644 index f2096cf9d..000000000 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.html +++ /dev/null @@ -1,15 +0,0 @@ -

"If possible, utilisation of svg image format is recommended over other image format.

-

Noncompliant Code Example

-
-    jEditorPane.setContentType("text/html");
-    jEditorPane.setText("\"Grapefruit\"");
-
-

Compliant Solution

-
-    jEditorPane.setContentType("text/html");
-    jEditorPane.setText("\"Grapefruit\"");
-
diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.json deleted file mode 100644 index 199e43d9c..000000000 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/CRJVM204.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "title": "Detect unoptimized image format", - "type": "CODE_SMELL", - "status": "ready", - "remediation": { - "func": "Constant\/Issue", - "constantCost": "15min" - }, - "tags": [ - "eco-design", - "bug", - "ecocode" - ], - "defaultSeverity": "Minor" -} diff --git a/java-plugin/src/test/files/DetectUnoptimizedImageFormat.java b/java-plugin/src/test/files/DetectUnoptimizedImageFormat.java deleted file mode 100644 index c8c631820..000000000 --- a/java-plugin/src/test/files/DetectUnoptimizedImageFormat.java +++ /dev/null @@ -1,84 +0,0 @@ -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.LayoutManager; -import java.io.IOException; -import java.net.URL; - -import javax.swing.JEditorPane; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - -public class DetectUnoptimizedImageFormat { - - private String img_bmp = "test/image.bmp"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - private String img_ico = "image.ico"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - private String img_tiff = "test/path/to/image.tiff"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - private String img_webp = "test/path/to/" + "image.webp"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - private String img_jpg = "image.jpg"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - private String img_jpeg = "image.jpeg"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - private String img_jfif = "image.jfif"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - private String img_pjpeg = "image.pjpeg"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - private String img_pjp = "image.pjp"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - private String img_gif = "image.gif"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - private String img_avif = "image.avif"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - private String img_apng = "image.apng"; // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - - - private static String getImagePath(String image) { - return "path/to/" + image; - } - - private static void testImage() { - String img1 = getImagePath("test/image.bmp"); // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - String img2 = getImagePath("image.ico"); // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - String img3 = getImagePath("image.jpg"); // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - } - - private static void createWindow() { - JFrame frame = new JFrame("Swing Tester"); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - createUI(frame); - frame.setSize(560, 450); - frame.setLocationRelativeTo(null); - frame.setVisible(true); - } - - private static void createUI(final JFrame frame) { - JPanel panel = new JPanel(); - LayoutManager layout = new FlowLayout(); - panel.setLayout(layout); - - JEditorPane jEditorPane = new JEditorPane(); - jEditorPane.setEditable(false); - - jEditorPane.setContentType("text/html"); - jEditorPane.setText("Le titre avec une partie en gras," + - " et une autre partie en bleu." + - " html tag) is recommended over other image format.}} - " alt=\"Grapefruit slice atop a pile of other slices\">" + - " \"Grapefruit" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.bmp\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.tiff\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.webp\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.png\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.jpeg\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.jfif\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.pjpeg\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.pjp\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.gif\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.avif\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - " src=\"/media/cc0-images/grapefruit-slice-332-332.apng\" alt=\"Grapefruit slice atop a pile of other slices\">" + // Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - ""); - - JScrollPane jScrollPane = new JScrollPane(jEditorPane); - jScrollPane.setPreferredSize(new Dimension(540, 400)); - - panel.add(jScrollPane); - panel.add(jScrollPane2); - frame.getContentPane().add(panel, BorderLayout.CENTER); - } -} \ No newline at end of file diff --git a/java-plugin/src/test/files/DetectUnoptimizedImageFormatComplient.java b/java-plugin/src/test/files/DetectUnoptimizedImageFormatComplient.java deleted file mode 100644 index c0ce54011..000000000 --- a/java-plugin/src/test/files/DetectUnoptimizedImageFormatComplient.java +++ /dev/null @@ -1,69 +0,0 @@ -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.LayoutManager; -import java.io.IOException; -import java.net.URL; - -import javax.swing.JEditorPane; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - -public class DetectUnoptimizedImageFormat { - - private String img_svg = "test/image.svg"; // Complient - - private String getImagePath(String image) { - return "path/to/" + image; - } - - private static void testImage() { - String img1 = getImagePath("test/image.svg"); // Complient - String img2 = getImagePath("image.svg"); // Complient - } - - private static void createWindow() { - JFrame frame = new JFrame("Swing Tester"); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - createUI(frame); - frame.setSize(560, 450); - frame.setLocationRelativeTo(null); - frame.setVisible(true); - } - - private static void createUI(final JFrame frame) { - JPanel panel = new JPanel(); - LayoutManager layout = new FlowLayout(); - panel.setLayout(layout); - - JEditorPane jEditorPane = new JEditorPane(); - jEditorPane.setEditable(false); - - jEditorPane.setContentType("text/html"); - jEditorPane.setText("Le titre avec une partie en gras," + - " et une autre partie en bleu." + - " \"Grapefruit" + - ""); - - JEditorPane jEditorPane1 = new JEditorPane(); - jEditorPane1.setEditable(false); - - jEditorPane1.setContentType("text/html"); - jEditorPane1.setText("Le titre avec une partie en gras," + - " et une autre partie en bleu." + - " " + // Complient - " " + - ""); - - JScrollPane jScrollPane = new JScrollPane(jEditorPane); - jScrollPane.setPreferredSize(new Dimension(540, 400)); - - panel.add(jScrollPane); - panel.add(jScrollPane2); - panel.add(jScrollPane3); - frame.getContentPane().add(panel, BorderLayout.CENTER); - } -} \ No newline at end of file diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormatTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormatTest.java deleted file mode 100644 index d2bd21858..000000000 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/DetectUnoptimizedImageFormatTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package fr.greencodeinitiative.java.checks; - -import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.CheckVerifier; - -public class DetectUnoptimizedImageFormatTest { - - @Test - void test() { - CheckVerifier.newVerifier() - .onFile("src/test/files/DetectUnoptimizedImageFormat.java") - .withCheck(new DetectUnoptimizedImageFormat()) - .verifyIssues(); - } - - @Test - void testComplient() { - CheckVerifier.newVerifier() - .onFile("src/test/files/DetectUnoptimizedImageFormatComplient.java") - .withCheck(new DetectUnoptimizedImageFormat()) - .verifyNoIssues(); - } -} diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/CRPYT203.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/CRPYT203.html index b7ca91bdf..a588eef95 100644 --- a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/CRPYT203.html +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/CRPYT203.html @@ -1,20 +1,46 @@ -

If possible, the utilisation of svg image format (or html tag) is recommended over other image format.

+

If possible, the utilisation of svg image format (or <svg/> html tag) is recommended over other image format.

+

Because SVGs are generally smaller than other image format, they’re less taxing on your server despite needing to render on load.

+

When to use SVG : +

    +
  • Your image is used for decorative website graphics, logos, icons, graphs and diagrams, and other simple images.
  • +
  • You image require animation.
  • +
  • You image need to be responsive and scale without lack of quality.
  • +
+

+

Some advantages of using SVG : +

    +
  • SVGs are scalable and will render pixel-perfect at any resolution whereas JPEGs, PNGs and GIFs will not.
  • +
  • SVGs are vector images and therefore are usually much smaller in file-size than bitmap-based images.
  • +
  • SVGs can be embedded into the HTML which means they can be cached, edited directly using CSS and indexed for greater accessibility.
  • +
  • SVGs can be animated directly or by using CSS or JavaScript making it easy for web designers to add interactivity to a site.
  • +
+

+ +

Noncompliant Code Example

+
+    ...
+    img_jpg = "image.jpg"
+    ...
+
+

Compliant Solution

+
+    ...
+    img_svg = "image.svg"
+    ...
+

Noncompliant Code Example

     public void foo() {
         ...
-        img_jpg = "image.jpg"
+        image_format = testImage("image.jpg")
         ...
     }
-
 

Compliant Solution

-
     public void foo() {
         ...
-        img_svg = "image.svg"
+        image_format = testImage("image.svg")
         ...
    }
-
 
From 56e65bc74a4845f5406a49feb3384ae247c01d3c Mon Sep 17 00:00:00 2001 From: plougastela Date: Thu, 6 Apr 2023 13:15:31 +0200 Subject: [PATCH 011/170] CRPYT203 - Detect unoptimized image format --- .../python/checks/DetectUnoptimizedImageFormat.java | 10 +++++++++- .../python/rules/python/{CRPYT203.html => EC203.html} | 0 .../python/PythonRuleRepositoryTest.java | 4 ++-- 3 files changed, 11 insertions(+), 3 deletions(-) rename python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/{CRPYT203.html => EC203.html} (100%) diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java index 8db89d276..efbbd0b2f 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java @@ -1,6 +1,8 @@ package fr.greencodeinitiative.python.checks; import com.sun.source.tree.LiteralTree; +import org.sonar.check.Priority; +import org.sonar.check.Rule; import org.sonar.plugins.python.api.PythonSubscriptionCheck; import org.sonar.plugins.python.api.SubscriptionContext; import org.sonar.plugins.python.api.tree.StringLiteral; @@ -9,9 +11,15 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +@Rule( + key = DetectUnoptimizedImageFormat.RULE_KEY, + name = "Detect unoptimized image format", + description = DetectUnoptimizedImageFormat.MESSAGEERROR, + priority = Priority.MINOR, + tags = {"bug", "eco-design", "ecocode"}) public class DetectUnoptimizedImageFormat extends PythonSubscriptionCheck { - public static final String RULE_KEY = "CRPYT203"; + public static final String RULE_KEY = "EC203"; protected static final String MESSAGERULE = "Detect unoptimized image format"; protected static final String MESSAGEERROR = "If possible, the utilisation of svg image format (or html tag) is recommended over other image format."; diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/CRPYT203.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html similarity index 100% rename from python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/CRPYT203.html rename to python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java index 101ff2841..f724dd805 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java @@ -44,8 +44,8 @@ public void init() { public void test() { assertThat(pythonRuleRepository.repositoryKey()).isEqualTo(PythonRuleRepository.REPOSITORY_KEY); assertThat(context.repositories()).hasSize(1).extracting("key").containsExactly(pythonRuleRepository.repositoryKey()); - assertThat(context.repositories().get(0).rules()).hasSize(6); - assertThat(pythonRuleRepository.checkClasses()).hasSize(6); + assertThat(context.repositories().get(0).rules()).hasSize(7); + assertThat(pythonRuleRepository.checkClasses()).hasSize(7); } From 37d029c3d0b7e21cf0f1c8434c3df2bb0ee80e69 Mon Sep 17 00:00:00 2001 From: plougastela Date: Thu, 6 Apr 2023 13:20:15 +0200 Subject: [PATCH 012/170] CRPYT203 - Detect unoptimized image format --- .../python/checks/DetectUnoptimizedImageFormat.java | 9 ++++----- .../python/checks/DetectUnoptimizedImageFormatTest.java | 2 +- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java index efbbd0b2f..644879979 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java @@ -13,17 +13,16 @@ @Rule( key = DetectUnoptimizedImageFormat.RULE_KEY, - name = "Detect unoptimized image format", + name = DetectUnoptimizedImageFormat.MESSAGERULE, description = DetectUnoptimizedImageFormat.MESSAGEERROR, priority = Priority.MINOR, tags = {"bug", "eco-design", "ecocode"}) public class DetectUnoptimizedImageFormat extends PythonSubscriptionCheck { - public static final String RULE_KEY = "EC203"; - + protected static final String RULE_KEY = "EC203"; protected static final String MESSAGERULE = "Detect unoptimized image format"; protected static final String MESSAGEERROR = "If possible, the utilisation of svg image format (or html tag) is recommended over other image format."; - protected static Pattern IMG_EXTENSION = Pattern.compile("\\.(bmp|ico|tiff|webp|png|jpg|jpeg|jfif|pjpeg|pjp|gif|avif|apng)"); + protected static Pattern IMGEXTENSION = Pattern.compile("\\.(bmp|ico|tiff|webp|png|jpg|jpeg|jfif|pjpeg|pjp|gif|avif|apng)"); @Override public void initialize(Context context) { @@ -34,7 +33,7 @@ public void visitNodeString(SubscriptionContext ctx) { if (ctx.syntaxNode().is(Tree.Kind.STRING_LITERAL)) { final StringLiteral stringLiteral = (StringLiteral) ctx.syntaxNode(); final String strValue = stringLiteral.trimmedQuotesValue(); - final Matcher matcher = IMG_EXTENSION.matcher(strValue); + final Matcher matcher = IMGEXTENSION.matcher(strValue); if(matcher.find()) { ctx.addIssue(stringLiteral, MESSAGEERROR); } diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java index a65679236..814d280cf 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java @@ -3,7 +3,7 @@ import org.junit.Test; import org.sonar.python.checks.utils.PythonCheckVerifier; -public class DetectUnoptimizedImageFormatTest { +class DetectUnoptimizedImageFormatTest { @Test public void test() { From 170ae16a788d0bdeb2754e58aad51105d515a777 Mon Sep 17 00:00:00 2001 From: plougastela Date: Thu, 6 Apr 2023 13:21:12 +0200 Subject: [PATCH 013/170] CRPYT203 - Detect unoptimized image format --- .../python/checks/DetectUnoptimizedImageFormat.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java index 644879979..098d00fcc 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java @@ -22,7 +22,7 @@ public class DetectUnoptimizedImageFormat extends PythonSubscriptionCheck { protected static final String RULE_KEY = "EC203"; protected static final String MESSAGERULE = "Detect unoptimized image format"; protected static final String MESSAGEERROR = "If possible, the utilisation of svg image format (or html tag) is recommended over other image format."; - protected static Pattern IMGEXTENSION = Pattern.compile("\\.(bmp|ico|tiff|webp|png|jpg|jpeg|jfif|pjpeg|pjp|gif|avif|apng)"); + protected static final Pattern IMGEXTENSION = Pattern.compile("\\.(bmp|ico|tiff|webp|png|jpg|jpeg|jfif|pjpeg|pjp|gif|avif|apng)"); @Override public void initialize(Context context) { From c708d03077ed22cac3bd5dd5672b3d1ccfd0b30f Mon Sep 17 00:00:00 2001 From: plougastela Date: Thu, 6 Apr 2023 13:26:04 +0200 Subject: [PATCH 014/170] CRPYT203 - Detect unoptimized image format --- .../fr/greencodeinitiative/l10n/python/rules/python/EC203.html | 1 + 1 file changed, 1 insertion(+) diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html index a588eef95..78ef52f8e 100644 --- a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html @@ -16,6 +16,7 @@

+

Noncompliant Code Example

     ...

From f64dbef9ab2a4a3310ae93055e79233814376502 Mon Sep 17 00:00:00 2001
From: plougastela 
Date: Thu, 6 Apr 2023 13:46:36 +0200
Subject: [PATCH 015/170] CRPYT203 - Detect unoptimized image format

---
 .../python/PythonRuleRepository.java          | 10 +++----
 .../l10n/python/rules/python/EC203.html       | 26 +++++++++++++++++++
 2 files changed, 29 insertions(+), 7 deletions(-)

diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java
index 2a6f0225c..fb49a37f8 100644
--- a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java
+++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java
@@ -29,12 +29,7 @@
 import java.util.List;
 import java.util.Map;
 
-import fr.greencodeinitiative.python.checks.AvoidFullSQLRequest;
-import fr.greencodeinitiative.python.checks.AvoidGettersAndSetters;
-import fr.greencodeinitiative.python.checks.AvoidGlobalVariableInFunctionCheck;
-import fr.greencodeinitiative.python.checks.AvoidSQLRequestInLoop;
-import fr.greencodeinitiative.python.checks.AvoidTryCatchFinallyCheck;
-import fr.greencodeinitiative.python.checks.NoFunctionCallWhenDeclaringForLoop;
+import fr.greencodeinitiative.python.checks.*;
 import org.apache.commons.lang.StringUtils;
 import org.sonar.api.server.rule.RulesDefinition;
 import org.sonar.api.server.rule.RulesDefinitionAnnotationLoader;
@@ -92,7 +87,8 @@ public List checkClasses() {
             AvoidSQLRequestInLoop.class,
             AvoidTryCatchFinallyCheck.class,
             NoFunctionCallWhenDeclaringForLoop.class,
-            AvoidFullSQLRequest.class
+            AvoidFullSQLRequest.class,
+            DetectUnoptimizedImageFormat.class
     );
   }
 
diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html
index 78ef52f8e..65516edfc 100644
--- a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html
+++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html
@@ -29,6 +29,7 @@ 

Compliant Solution

img_svg = "image.svg" ...
+

Noncompliant Code Example

     public void foo() {
@@ -45,3 +46,28 @@ 

Compliant Solution

... }
+ +

Noncompliant Code Example

+
+    public void foo() {
+        ...
+        return '<html><img src="xx/xx/image.bmp"></html>'
+        ...
+    }
+
+

Compliant Solution

+
+    public void foo() {
+        ...
+        return '<html><img src="xx/xx/image.svg"></html>'
+        ...
+   }
+
+     public void foo2() {
+        ...
+        return ('<html><svg width="100" height="100">' +
+                '<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />' +
+                '</svg></html>')
+        ...
+   }
+
From 9aad7e72e652d5cf2bb13ab5fdadea1232cfbefc Mon Sep 17 00:00:00 2001 From: plougastela Date: Thu, 6 Apr 2023 13:57:04 +0200 Subject: [PATCH 016/170] CRPYT203 - Detect unoptimized image format --- .../python/checks/DetectUnoptimizedImageFormatTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java index 814d280cf..a65679236 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java @@ -3,7 +3,7 @@ import org.junit.Test; import org.sonar.python.checks.utils.PythonCheckVerifier; -class DetectUnoptimizedImageFormatTest { +public class DetectUnoptimizedImageFormatTest { @Test public void test() { From 5eedcf92274448ddc6def1d74695c168c89a76b2 Mon Sep 17 00:00:00 2001 From: plougastela Date: Thu, 6 Apr 2023 14:00:32 +0200 Subject: [PATCH 017/170] CRPYT203 - Detect unoptimized image format --- .../python/checks/DetectUnoptimizedImageFormat.java | 1 - 1 file changed, 1 deletion(-) diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java index 098d00fcc..c680040da 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java @@ -1,6 +1,5 @@ package fr.greencodeinitiative.python.checks; -import com.sun.source.tree.LiteralTree; import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.python.api.PythonSubscriptionCheck; From 4549cd089bb21f41a397fcd544d748d50fdeca40 Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Thu, 6 Apr 2023 14:35:00 +0200 Subject: [PATCH 018/170] doc: fix compliant and non compliant solutions html --- .../greencodeinitiative/l10n/python/rules/python/EC404.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC404.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC404.html index 0e48db385..f7c47727f 100644 --- a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC404.html +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC404.html @@ -3,11 +3,11 @@

For more details on list comprehensions vs generator comprehensions, see Python documentation.

Noncompliant Code Example

-for var in [for var2 in range(100)]:
+for var in [var2 for var2 in range(100)]:
     ...
 

Compliant Solution

-for var in (for var2 in range(100)):
+for var in (var2 for var2 in range(100)):
     ...
 
From 4b6e227059f3efbdcdbb36b8ad8ee54fa2746b96 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Thu, 6 Apr 2023 18:38:04 +0200 Subject: [PATCH 019/170] EC3 PHP Avoid Getting Size Collection In For Loop --- .../php/PhpRuleRepository.java | 12 +-- ...idGettingSizeCollectionInForLoopCheck.java | 65 +++++++++++++++ .../l10n/php/rules/custom/EC3.html | 55 +++++++++++++ .../php/PhpRuleRepositoryTest.java | 4 +- ...oidGettingSizeCollectionInForLoopTest.java | 15 ++++ .../AvoidGettingSizeCollectionInForLoop.php | 79 +++++++++++++++++++ 6 files changed, 219 insertions(+), 11 deletions(-) create mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java create mode 100644 php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html create mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopTest.java create mode 100644 php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java index a8cd4fd70..e89b33016 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java @@ -30,14 +30,7 @@ import java.util.Map; import com.google.common.collect.ImmutableList; -import fr.greencodeinitiative.php.checks.AvoidDoubleQuoteCheck; -import fr.greencodeinitiative.php.checks.AvoidFullSQLRequestCheck; -import fr.greencodeinitiative.php.checks.AvoidSQLRequestInLoopCheck; -import fr.greencodeinitiative.php.checks.AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements; -import fr.greencodeinitiative.php.checks.AvoidUsingGlobalVariablesCheck; -import fr.greencodeinitiative.php.checks.IncrementCheck; -import fr.greencodeinitiative.php.checks.NoFunctionCallWhenDeclaringForLoop; -import fr.greencodeinitiative.php.checks.UseOfMethodsForBasicOperations; +import fr.greencodeinitiative.php.checks.*; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.api.server.rule.RulesDefinitionAnnotationLoader; import org.sonar.plugins.php.api.visitors.PHPCustomRuleRepository; @@ -88,7 +81,8 @@ public String repositoryKey() { @Override public List> checkClasses() { - return ImmutableList.of( + return List.of( + AvoidGettingSizeCollectionInForLoopCheck.class, AvoidDoubleQuoteCheck.class, AvoidFullSQLRequestCheck.class, AvoidSQLRequestInLoopCheck.class, diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java new file mode 100644 index 000000000..fa5bc8cd0 --- /dev/null +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java @@ -0,0 +1,65 @@ +package fr.greencodeinitiative.php.checks; + +import org.sonar.check.Priority; +import org.sonar.check.Rule; +import org.sonar.plugins.php.api.tree.SeparatedList; +import org.sonar.plugins.php.api.tree.Tree; +import org.sonar.plugins.php.api.tree.expression.BinaryExpressionTree; +import org.sonar.plugins.php.api.tree.expression.ExpressionTree; +import org.sonar.plugins.php.api.tree.expression.ParenthesisedExpressionTree; +import org.sonar.plugins.php.api.tree.statement.*; +import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; + +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; + +@Rule( + key = AvoidGettingSizeCollectionInForLoopCheck.RULE_KEY, + name = AvoidGettingSizeCollectionInForLoopCheck.ERROR_MESSAGE, + description = AvoidGettingSizeCollectionInForLoopCheck.ERROR_MESSAGE, + priority = Priority.MINOR, + tags = {"bug", "eco-design", "ecocode"}) +public class AvoidGettingSizeCollectionInForLoopCheck extends PHPSubscriptionCheck { + + public static final String RULE_KEY = "EC3"; + public static final String ERROR_MESSAGE = "Avoid getting the size of the collection in the loop"; + private static final Pattern PATTERN = Pattern.compile("\\b(?:count|sizeof)\\b"); + + @Override + public List nodesToVisit() { + return Arrays.asList(Tree.Kind.FOR_STATEMENT, Tree.Kind.WHILE_STATEMENT, Tree.Kind.DO_WHILE_STATEMENT); + } + + @Override + public void visitNode(Tree tree) { + if (tree.is(Tree.Kind.FOR_STATEMENT)) { + ForStatementTree conditionTree = (ForStatementTree) tree; + SeparatedList conditions = conditionTree.condition(); + + for (ExpressionTree condition : conditions) { + if (condition instanceof BinaryExpressionTree) { + verifyIfThereIsAError(((BinaryExpressionTree) condition).rightOperand().toString(), conditionTree); + } + } + } + + if (tree.is(Tree.Kind.WHILE_STATEMENT)) { + WhileStatementTree whileTree = (WhileStatementTree) tree; + ParenthesisedExpressionTree condition = whileTree.condition(); + verifyIfThereIsAError(condition.expression().toString(), whileTree); + } + + if (tree.is(Tree.Kind.DO_WHILE_STATEMENT)) { + DoWhileStatementTree doWhileTree = (DoWhileStatementTree) tree; + ParenthesisedExpressionTree condition = doWhileTree.condition(); + verifyIfThereIsAError(condition.expression().toString(), doWhileTree); + } + } + + private void verifyIfThereIsAError(String condition, StatementTree conditionTree) { + if (PATTERN.matcher(condition).find()) { + context().newIssue(this, conditionTree, ERROR_MESSAGE); + } + } +} diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html new file mode 100644 index 000000000..f7ac23654 --- /dev/null +++ b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html @@ -0,0 +1,55 @@ +

When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power.

+ +

Noncompliant Code Example

+
+	$food = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
+
+	// FOR STATEMENTS
+	for ($i = 0; $i < count($food); $i++) {
+		var_dump($food[$i]);
+	}
+
+	// WHILE STATEMENTS
+	$i = 0;
+	while($i < count($food))
+	{
+		var_dump($food[$i]);
+		$i++;
+	}
+
+	// DO WHILE STATEMENTS
+	$i = 0;
+	do {
+		var_dump($food[$i]);
+		$i++;
+	} while ($i < count($food));
+
+
+ +

Compliant Solution

+
+	$food = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
+	// FOR STATEMENTS
+	$size = sizeof($food);
+	for ($i = 0; $i < $size; $i++) {
+		var_dump($food[$i]);
+	}
+
+	// WHILE STATEMENTS
+	$i = 0;
+	$size = count($food);
+	while($i < $size)
+	{
+		var_dump($food[$i]);
+		$i++;
+	}
+
+	// DO WHILE STATEMENTS
+	$i = 0;
+	$size = count($food);
+	do {
+		var_dump($food[$i]);
+		$i++;
+	} while ($i < $size);
+
+
diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java index f2345716d..3a124f382 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java @@ -41,8 +41,8 @@ public void init() { public void test() { assertThat(phpRuleRepository.repositoryKey()).isEqualTo(PhpRuleRepository.REPOSITORY_KEY); assertThat(context.repositories()).hasSize(1).extracting("key").containsExactly(phpRuleRepository.repositoryKey()); - assertThat(context.repositories().get(0).rules()).hasSize(8); - assertThat(phpRuleRepository.checkClasses()).hasSize(8); + assertThat(context.repositories().get(0).rules()).hasSize(9); + assertThat(phpRuleRepository.checkClasses()).hasSize(9); } /** diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopTest.java new file mode 100644 index 000000000..9e527c140 --- /dev/null +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopTest.java @@ -0,0 +1,15 @@ +package fr.greencodeinitiative.php.checks; + +import org.junit.Test; +import org.sonar.plugins.php.api.tests.PHPCheckTest; +import org.sonar.plugins.php.api.tests.PhpTestFile; + +import java.io.File; + +public class AvoidGettingSizeCollectionInForLoopTest { + + @Test + public void test() throws Exception { + PHPCheckTest.check(new AvoidGettingSizeCollectionInForLoopCheck(), new PhpTestFile(new File("src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php"))); + } +} diff --git a/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php b/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php new file mode 100644 index 000000000..4fa8d242b --- /dev/null +++ b/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php @@ -0,0 +1,79 @@ + Date: Thu, 13 Apr 2023 23:43:38 +0200 Subject: [PATCH 020/170] update CHANGELOG --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ca102b523..4d6548bc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,7 +25,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#63](https://github.com/green-code-initiative/ecoCode/issues/63) Update plugins to be compliant for SonarQube MarketPlace integration ( PR [#79](https://github.com/green-code-initiative/ecoCode/pull/79) ) - [#88](https://github.com/green-code-initiative/ecoCode/pull/88) upgrade rules matrix with new ids + refactoring rules documentation (`RULES.md`) - - _*WARNING*_ : since this plugin version, ids of plugin rules changed. In consequence, if you have already made some issue checks in your SonarQube instance, you will have to do them again (example : false-positive issues will appear again) ### Deleted From 4d995451a7a0ee1eee4f830eb264169b08ace1c9 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 14 Apr 2023 09:52:26 +0200 Subject: [PATCH 021/170] [ISSUE 173] correction of unit tests :( --- .../avoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php | 4 ++-- .../src/test/resources/checks/avoidTryCatchFinallyCheck.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/php-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php b/php-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php index 22a44564c..1698df424 100644 --- a/php-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php +++ b/php-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php @@ -7,7 +7,7 @@ function test() { throw new SpecificException('Oopsie'); } -try // NOK {{Avoid using try-catch-finally}} +try // NOK {{Avoid using try-catch}} { $picture = PDF_open_image_file($PDF, "jpeg", $imgFile, "", 0); // This is the original statement, this works on PHP4 } @@ -17,7 +17,7 @@ function test() { throw new Exception($msg); } -try { // NOK {{Avoid using try-catch-finally}} +try { // NOK {{Avoid using try-catch}} throw new \Exception("Hello"); } catch(\Exception $e) { echo $e->getMessage()." catch in\n"; diff --git a/python-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck.py b/python-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck.py index a026587ed..1e24bb491 100644 --- a/python-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck.py +++ b/python-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck.py @@ -6,7 +6,7 @@ def my_function(): x=0 - try: # Noncompliant {{Avoid the use of try-catch-finally}} + try: # Noncompliant {{Avoid the use of try-catch}} print(x) except: print("Something went wrong") @@ -14,7 +14,7 @@ def my_function(): print("The 'try except' is finished") def foo(): - try: # Noncompliant {{Avoid the use of try-catch-finally}} + try: # Noncompliant {{Avoid the use of try-catch}} f = open(path) print(f.read()) except: From 56a4498ec9825264520225324da9c6ce290d2a11 Mon Sep 17 00:00:00 2001 From: Ludovic BOSSE <63793941+natixis-caen@users.noreply.github.com> Date: Fri, 14 Apr 2023 10:05:54 +0200 Subject: [PATCH 022/170] [ISSUE 161] :heavy_minus_sign: Remove unused junit dependency --- CHANGELOG.md | 1 + java-plugin/pom.xml | 6 ------ javascript-plugin/pom.xml | 6 ++---- .../javascript/JavaScriptPluginTest.java | 6 +++--- .../javascript/JavaScriptRulesDefinitionTest.java | 6 +++--- php-plugin/pom.xml | 7 ------- pom.xml | 15 --------------- python-plugin/pom.xml | 6 ------ 8 files changed, 9 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d6548bc1..cf6f01553 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [171](https://github.com/green-code-initiative/ecoCode/issues/171) Add migration mechanism to support "issue re-keying" ### Changed +- [#161](https://github.com/green-code-initiative/ecoCode/pull/161) Remove unnecessary junit dependencies in pom.xml - [166](https://github.com/green-code-initiative/ecoCode/issues/166) Correction of wrong message of rule EC63 - [167](https://github.com/green-code-initiative/ecoCode/issues/167) Use same kind for rules across different languages diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index 6e5e11f38..88ba0c619 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -69,12 +69,6 @@ test - - org.junit.jupiter - junit-jupiter-migrationsupport - test - - org.assertj assertj-core diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml index 8412187ea..379b9f388 100644 --- a/javascript-plugin/pom.xml +++ b/javascript-plugin/pom.xml @@ -38,11 +38,9 @@ sonar-analyzer-commons - - - junit - junit + org.junit.jupiter + junit-jupiter test diff --git a/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java b/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java index a558e0626..ad50f25ec 100644 --- a/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java +++ b/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java @@ -1,15 +1,15 @@ package fr.greencodeinitiative.javascript; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.sonar.api.*; import org.sonar.api.utils.Version; import static org.assertj.core.api.Assertions.assertThat; -public class JavaScriptPluginTest { +class JavaScriptPluginTest { @Test - public void extensions() { + void extensions() { Plugin.Context context = new Plugin.Context(new MockedSonarRuntime()); new JavaScriptPlugin().define(context); assertThat(context.getExtensions()).hasSize(1); diff --git a/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinitionTest.java b/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinitionTest.java index 60bdc8510..e90f75d95 100644 --- a/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinitionTest.java +++ b/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinitionTest.java @@ -1,14 +1,14 @@ package fr.greencodeinitiative.javascript; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.sonar.api.server.rule.RulesDefinition; import static org.assertj.core.api.Assertions.assertThat; -public class JavaScriptRulesDefinitionTest { +class JavaScriptRulesDefinitionTest { @Test - public void createExternalRepository() { + void createExternalRepository() { RulesDefinition.Context context = new RulesDefinition.Context(); new JavaScriptRulesDefinition().define(context); assertThat(context.repositories()).hasSize(1); diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index a79f181ef..0180065c8 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -40,18 +40,11 @@ - - junit - junit - test - - org.assertj assertj-core test - diff --git a/pom.xml b/pom.xml index 83d26a01e..c778ffec3 100644 --- a/pom.xml +++ b/pom.xml @@ -67,7 +67,6 @@ 1.21.0.505 true 3.4.1 - 4.13.2 5.9.1 3.23.1 @@ -156,13 +155,6 @@ test - - org.junit.jupiter - junit-jupiter-migrationsupport - ${junit.jupiter.version} - test - - org.assertj assertj-core @@ -170,13 +162,6 @@ test - - junit - junit - ${junit.version} - test - - org.sonarsource.python python-checks-testkit diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index bfef526ff..cbc4d6906 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -44,12 +44,6 @@ test - - junit - junit - test - - From 3021907849a70d460923f44c14a824b51b395ddb Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 14 Apr 2023 10:08:05 +0200 Subject: [PATCH 023/170] [ISSUE 173] correction issue description --- .../python/checks/AvoidTryCatchFinallyCheck.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java index 2d70e97f3..70197a1e3 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java @@ -10,7 +10,7 @@ @Rule( key = AvoidTryCatchFinallyCheck.RULE_KEY, - name = "Avoid using try-catch-finally statement", + name = "Avoid using try-catch statement", description = AvoidTryCatchFinallyCheck.DESCRIPTION, priority = Priority.MINOR, tags = {"bug", "eco-design", "ecocode"}) From e88624351e43de411ebb3cc29f5f4f6474162a4d Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 14 Apr 2023 10:08:18 +0200 Subject: [PATCH 024/170] upgrade CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf6f01553..84c2ca3b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,8 +12,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [171](https://github.com/green-code-initiative/ecoCode/issues/171) Add migration mechanism to support "issue re-keying" ### Changed -- [#161](https://github.com/green-code-initiative/ecoCode/pull/161) Remove unnecessary junit dependencies in pom.xml +- [#161](https://github.com/green-code-initiative/ecoCode/pull/161) Remove unnecessary junit dependencies in pom.xml - [166](https://github.com/green-code-initiative/ecoCode/issues/166) Correction of wrong message of rule EC63 - [167](https://github.com/green-code-initiative/ecoCode/issues/167) Use same kind for rules across different languages - [173](https://github.com/green-code-initiative/ecoCode/issues/173) Update issue description of rule EC34 (try-catch) From 9cdd98c2b67a1b4f867908125e52d3221a2bcd5b Mon Sep 17 00:00:00 2001 From: Ludovic BOSSE <63793941+natixis-caen@users.noreply.github.com> Date: Fri, 14 Apr 2023 11:11:05 +0200 Subject: [PATCH 025/170] [ISSUE 177] Rename property in pom (#177) --- pom.xml | 13 +++++++------ python-plugin/pom.xml | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index c778ffec3..6841635cb 100644 --- a/pom.xml +++ b/pom.xml @@ -51,7 +51,6 @@ ${encoding} 9.4.0.54424 - 7.15.0.30507 green-code-initiative https://sonarcloud.io @@ -59,11 +58,13 @@ 0.8.8 - 9.7.1.62043 - 2.1.0.1111 - 3.19.0.10254 + 7.15.0.30507 + 3.19.0.10254 3.25.0.9077 9.13.0.20537 + + 9.7.1.62043 + 2.1.0.1111 1.21.0.505 true 3.4.1 @@ -135,7 +136,7 @@ org.sonarsource.python sonar-python-plugin - ${sonar.python.version} + ${sonarpython.version} sonar-plugin provided @@ -165,7 +166,7 @@ org.sonarsource.python python-checks-testkit - ${sonar.python.version} + ${sonarpython.version} test diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index cbc4d6906..faa480543 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -57,7 +57,7 @@ ${project.name} fr.greencodeinitiative.python.PythonPlugin true - python:${sonar.python.version} + python:${sonarpython.version} ${sonarqube.version} ${java.version} From e1b16d29bee24e68226c24651a29d4d822420a42 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 14 Apr 2023 22:54:40 +0200 Subject: [PATCH 026/170] prepare 1.2.0 version --- docker-compose.yml | 16 ++++++++-------- java-plugin/pom.xml | 2 +- javascript-plugin/pom.xml | 2 +- php-plugin/pom.xml | 2 +- pom.xml | 2 +- python-plugin/pom.xml | 2 +- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index bc48387aa..e188f2bf0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,17 +16,17 @@ services: SONAR_ES_BOOTSTRAP_CHECKS_DISABLE: 'true' volumes: - type: bind - source: ./java-plugin/target/ecocode-java-plugin-1.1.1-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.1.1-SNAPSHOT.jar + source: ./java-plugin/target/ecocode-java-plugin-1.2.0-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.2.0-SNAPSHOT.jar - type: bind - source: ./javascript-plugin/target/ecocode-javascript-plugin-1.1.1-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-javascript-plugin-1.1.1-SNAPSHOT.jar + source: ./javascript-plugin/target/ecocode-javascript-plugin-1.2.0-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-javascript-plugin-1.2.0-SNAPSHOT.jar - type: bind - source: ./php-plugin/target/ecocode-php-plugin-1.1.1-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.1.1-SNAPSHOT.jar + source: ./php-plugin/target/ecocode-php-plugin-1.2.0-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.2.0-SNAPSHOT.jar - type: bind - source: ./python-plugin/target/ecocode-python-plugin-1.1.1-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-python-plugin-1.1.1-SNAPSHOT.jar + source: ./python-plugin/target/ecocode-python-plugin-1.2.0-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-python-plugin-1.2.0-SNAPSHOT.jar - "extensions:/opt/sonarqube/extensions" - "logs:/opt/sonarqube/logs" - "data:/opt/sonarqube/data" diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index 88ba0c619..7d08b5082 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.1.1-SNAPSHOT + 1.2.0-SNAPSHOT ecocode-java-plugin diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml index 379b9f388..353c00a1e 100644 --- a/javascript-plugin/pom.xml +++ b/javascript-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.1.1-SNAPSHOT + 1.2.0-SNAPSHOT ecocode-javascript-plugin diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index 0180065c8..675548ea8 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.1.1-SNAPSHOT + 1.2.0-SNAPSHOT ecocode-php-plugin diff --git a/pom.xml b/pom.xml index 6841635cb..0ce325dfe 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ io.ecocode ecocode-parent - 1.1.1-SNAPSHOT + 1.2.0-SNAPSHOT pom ecoCode Sonar Plugins Project diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index faa480543..280d64ba4 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.1.1-SNAPSHOT + 1.2.0-SNAPSHOT ecocode-python-plugin From 8f60ea11f74a0c7c5e92b36e56202753c8174b73 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 14 Apr 2023 22:57:39 +0200 Subject: [PATCH 027/170] prepare 1.2.0 version - CHANGELOG.md update --- CHANGELOG.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 84c2ca3b0..b97918436 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +### Changed + +### Deleted + +## [1.2.0] - 2023-04-14 + +### Added + - [171](https://github.com/green-code-initiative/ecoCode/issues/171) Add migration mechanism to support "issue re-keying" ### Changed @@ -108,9 +116,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - First official release of ecocode plugins : java plugin, php plugin and python plugin -[unreleased]: https://github.com/green-code-initiative/ecoCode/compare/v1.1.0...HEAD +[unreleased]: https://github.com/green-code-initiative/ecoCode/compare/v1.2.0...HEAD + +[1.2.0]: https://github.com/green-code-initiative/ecoCode/compare/v1.1.0...v1.2.0 -[1.0.0]: https://github.com/green-code-initiative/ecoCode/compare/v1.0.0...v1.1.0 +[1.1.0]: https://github.com/green-code-initiative/ecoCode/compare/v1.0.0...v1.1.0 [1.0.0]: https://github.com/green-code-initiative/ecoCode/compare/v0.2.2...v1.0.0 From 7354bec681c2e0bbbd43c07912e858ee9c6ecea9 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 14 Apr 2023 23:00:11 +0200 Subject: [PATCH 028/170] [maven-release-plugin] prepare release 1.2.0 --- java-plugin/pom.xml | 2 +- javascript-plugin/pom.xml | 2 +- php-plugin/pom.xml | 2 +- pom.xml | 4 ++-- python-plugin/pom.xml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index 7d08b5082..7abb551fa 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.0-SNAPSHOT + 1.2.0 ecocode-java-plugin diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml index 353c00a1e..7c8ff136a 100644 --- a/javascript-plugin/pom.xml +++ b/javascript-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.0-SNAPSHOT + 1.2.0 ecocode-javascript-plugin diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index 675548ea8..ce245a592 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.0-SNAPSHOT + 1.2.0 ecocode-php-plugin diff --git a/pom.xml b/pom.xml index 0ce325dfe..4c7d81730 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ io.ecocode ecocode-parent - 1.2.0-SNAPSHOT + 1.2.0 pom ecoCode Sonar Plugins Project @@ -33,7 +33,7 @@ scm:git:https://github.com/green-code-initiative/ecocode scm:git:https://github.com/green-code-initiative/ecocode https://github.com/green-code-initiative/ecocode - HEAD + 1.2.0 GitHub diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index 280d64ba4..7ea1007f6 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.0-SNAPSHOT + 1.2.0 ecocode-python-plugin From 7e21523d98246f34e69d07289dd84da098d00656 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 14 Apr 2023 23:00:12 +0200 Subject: [PATCH 029/170] [maven-release-plugin] prepare for next development iteration --- java-plugin/pom.xml | 2 +- javascript-plugin/pom.xml | 2 +- php-plugin/pom.xml | 2 +- pom.xml | 4 ++-- python-plugin/pom.xml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index 7abb551fa..49c99e88e 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.0 + 1.2.1-SNAPSHOT ecocode-java-plugin diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml index 7c8ff136a..56c1b52d6 100644 --- a/javascript-plugin/pom.xml +++ b/javascript-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.0 + 1.2.1-SNAPSHOT ecocode-javascript-plugin diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index ce245a592..1cef01679 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.0 + 1.2.1-SNAPSHOT ecocode-php-plugin diff --git a/pom.xml b/pom.xml index 4c7d81730..9a7d83e5c 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ io.ecocode ecocode-parent - 1.2.0 + 1.2.1-SNAPSHOT pom ecoCode Sonar Plugins Project @@ -33,7 +33,7 @@ scm:git:https://github.com/green-code-initiative/ecocode scm:git:https://github.com/green-code-initiative/ecocode https://github.com/green-code-initiative/ecocode - 1.2.0 + HEAD GitHub diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index 7ea1007f6..9529ebc29 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.0 + 1.2.1-SNAPSHOT ecocode-python-plugin From 32dbf33de1634681a3d613acd5b57b01e3509bec Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 14 Apr 2023 23:17:22 +0200 Subject: [PATCH 030/170] end of 1.2.0 release : change docker-compose to 1.2.1-SNAPSHOT --- docker-compose.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index e188f2bf0..6b7db1772 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,17 +16,17 @@ services: SONAR_ES_BOOTSTRAP_CHECKS_DISABLE: 'true' volumes: - type: bind - source: ./java-plugin/target/ecocode-java-plugin-1.2.0-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.2.0-SNAPSHOT.jar + source: ./java-plugin/target/ecocode-java-plugin-1.2.1-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.2.1-SNAPSHOT.jar - type: bind - source: ./javascript-plugin/target/ecocode-javascript-plugin-1.2.0-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-javascript-plugin-1.2.0-SNAPSHOT.jar + source: ./javascript-plugin/target/ecocode-javascript-plugin-1.2.1-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-javascript-plugin-1.2.1-SNAPSHOT.jar - type: bind - source: ./php-plugin/target/ecocode-php-plugin-1.2.0-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.2.0-SNAPSHOT.jar + source: ./php-plugin/target/ecocode-php-plugin-1.2.1-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.2.1-SNAPSHOT.jar - type: bind - source: ./python-plugin/target/ecocode-python-plugin-1.2.0-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-python-plugin-1.2.0-SNAPSHOT.jar + source: ./python-plugin/target/ecocode-python-plugin-1.2.1-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-python-plugin-1.2.1-SNAPSHOT.jar - "extensions:/opt/sonarqube/extensions" - "logs:/opt/sonarqube/logs" - "data:/opt/sonarqube/data" From 08938f422bb724418467ba853dff6b0f60c55935 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 14 Apr 2023 23:18:55 +0200 Subject: [PATCH 031/170] correction typo CHANGELOG.md --- CHANGELOG.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b97918436..fbde0393c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,14 +17,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- [171](https://github.com/green-code-initiative/ecoCode/issues/171) Add migration mechanism to support "issue re-keying" +- [#171](https://github.com/green-code-initiative/ecoCode/issues/171) Add migration mechanism to support "issue re-keying" ### Changed - [#161](https://github.com/green-code-initiative/ecoCode/pull/161) Remove unnecessary junit dependencies in pom.xml -- [166](https://github.com/green-code-initiative/ecoCode/issues/166) Correction of wrong message of rule EC63 -- [167](https://github.com/green-code-initiative/ecoCode/issues/167) Use same kind for rules across different languages -- [173](https://github.com/green-code-initiative/ecoCode/issues/173) Update issue description of rule EC34 (try-catch) +- [#166](https://github.com/green-code-initiative/ecoCode/issues/166) Correction of wrong message of rule EC63 +- [#167](https://github.com/green-code-initiative/ecoCode/issues/167) Use same kind for rules across different languages +- [#173](https://github.com/green-code-initiative/ecoCode/issues/173) Update issue description of rule EC34 (try-catch) ### Deleted From 2caa75272ed89ce958ba2e5f9030cdb69c2723aa Mon Sep 17 00:00:00 2001 From: jycr Date: Tue, 18 Apr 2023 01:05:46 +0200 Subject: [PATCH 032/170] green-code-initiative/ecoCode#63 fix: fixes metadata generation task from SonarSource/sonar-update-center-properties Since "core" analyzers have been integrated more tightly with SonarQube, they no longer appear on the Marketplace. So now plugins should no longer explicitly "require" their respective language "core" analyzers. More information: https://community.sonarsource.com/t/new-plugin-ecocode-requesting-inclusion-in-sonarqube-marketplace/85398/20 --- java-plugin/pom.xml | 10 ---------- javascript-plugin/pom.xml | 1 - php-plugin/pom.xml | 2 -- .../fr/greencodeinitiative/php/PhpRuleRepository.java | 4 +--- python-plugin/pom.xml | 1 - 5 files changed, 1 insertion(+), 17 deletions(-) diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index 49c99e88e..9daece94e 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -44,12 +44,6 @@ 3.11 - - com.google.guava - guava - 31.0.1-jre - - com.google.re2j @@ -89,10 +83,6 @@ fr.greencodeinitiative.java.JavaPlugin true ${sonarqube.version} - - - - java ${java.version} diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml index 56c1b52d6..f7d53dc99 100644 --- a/javascript-plugin/pom.xml +++ b/javascript-plugin/pom.xml @@ -64,7 +64,6 @@ fr.greencodeinitiative.javascript.JavaScriptPlugin true ${sonarqube.version} - javascript ${java.version} diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index 1cef01679..46492ca2c 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -59,9 +59,7 @@ fr.greencodeinitiative.php.PHPPlugin true ${sonarqube.version} - php ${java.version} - php:${sonarphp.version} ${sonarqube.version} ${java.version} diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java index bebb9e605..91d307a7e 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java @@ -24,12 +24,10 @@ 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 com.google.common.collect.ImmutableList; import fr.greencodeinitiative.php.checks.AvoidDoubleQuoteCheck; import fr.greencodeinitiative.php.checks.AvoidFullSQLRequestCheck; import fr.greencodeinitiative.php.checks.AvoidSQLRequestInLoopCheck; @@ -90,7 +88,7 @@ public String repositoryKey() { @Override public List> checkClasses() { - return ImmutableList.of( + return List.of( AvoidDoubleQuoteCheck.class, AvoidFullSQLRequestCheck.class, AvoidSQLRequestInLoopCheck.class, diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index 9529ebc29..cdfa76710 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -57,7 +57,6 @@ ${project.name} fr.greencodeinitiative.python.PythonPlugin true - python:${sonarpython.version} ${sonarqube.version} ${java.version} From 6ce15e2d7ee7204611eefba0d6a30828ba173fc9 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 18 Apr 2023 09:45:59 +0200 Subject: [PATCH 033/170] prepare 1.2.1 version - CHANGELOG.md update --- CHANGELOG.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fbde0393c..3b36e9b06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Deleted +## [1.2.1] - 2023-04-18 + +### Added + +### Changed + +- [#180](https://github.com/green-code-initiative/ecoCode/pull/180) correction of SonarQube review for MarketPlace (sonar plugin) + +### Deleted + ## [1.2.0] - 2023-04-14 ### Added @@ -116,7 +126,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - First official release of ecocode plugins : java plugin, php plugin and python plugin -[unreleased]: https://github.com/green-code-initiative/ecoCode/compare/v1.2.0...HEAD +[unreleased]: https://github.com/green-code-initiative/ecoCode/compare/v1.2.1...HEAD + +[1.2.1]: https://github.com/green-code-initiative/ecoCode/compare/v1.2.0...v1.2.1 [1.2.0]: https://github.com/green-code-initiative/ecoCode/compare/v1.1.0...v1.2.0 From 7565ab0eb8ef7087f3ada6346ca4ae1053f15850 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 18 Apr 2023 09:47:01 +0200 Subject: [PATCH 034/170] [maven-release-plugin] prepare release 1.2.1 --- java-plugin/pom.xml | 2 +- javascript-plugin/pom.xml | 2 +- php-plugin/pom.xml | 2 +- pom.xml | 4 ++-- python-plugin/pom.xml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index 9daece94e..fad3faeba 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.1-SNAPSHOT + 1.2.1 ecocode-java-plugin diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml index f7d53dc99..b2e3f073c 100644 --- a/javascript-plugin/pom.xml +++ b/javascript-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.1-SNAPSHOT + 1.2.1 ecocode-javascript-plugin diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index 46492ca2c..df91f1031 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.1-SNAPSHOT + 1.2.1 ecocode-php-plugin diff --git a/pom.xml b/pom.xml index 9a7d83e5c..688a9fa74 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ io.ecocode ecocode-parent - 1.2.1-SNAPSHOT + 1.2.1 pom ecoCode Sonar Plugins Project @@ -33,7 +33,7 @@ scm:git:https://github.com/green-code-initiative/ecocode scm:git:https://github.com/green-code-initiative/ecocode https://github.com/green-code-initiative/ecocode - HEAD + 1.2.1 GitHub diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index cdfa76710..60a6cd683 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.1-SNAPSHOT + 1.2.1 ecocode-python-plugin From 485f2dfe1796f507b2d79f87dd217b756a72b64d Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 18 Apr 2023 09:47:01 +0200 Subject: [PATCH 035/170] [maven-release-plugin] prepare for next development iteration --- java-plugin/pom.xml | 2 +- javascript-plugin/pom.xml | 2 +- php-plugin/pom.xml | 2 +- pom.xml | 4 ++-- python-plugin/pom.xml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index fad3faeba..acb1b601c 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.1 + 1.2.2-SNAPSHOT ecocode-java-plugin diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml index b2e3f073c..3349c963f 100644 --- a/javascript-plugin/pom.xml +++ b/javascript-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.1 + 1.2.2-SNAPSHOT ecocode-javascript-plugin diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index df91f1031..0910c07b5 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.1 + 1.2.2-SNAPSHOT ecocode-php-plugin diff --git a/pom.xml b/pom.xml index 688a9fa74..4f15d9b78 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ io.ecocode ecocode-parent - 1.2.1 + 1.2.2-SNAPSHOT pom ecoCode Sonar Plugins Project @@ -33,7 +33,7 @@ scm:git:https://github.com/green-code-initiative/ecocode scm:git:https://github.com/green-code-initiative/ecocode https://github.com/green-code-initiative/ecocode - 1.2.1 + HEAD GitHub diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index 60a6cd683..1a239fa51 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.1 + 1.2.2-SNAPSHOT ecocode-python-plugin From d7154361c5555d3b6dc0a4b8d09aedd69fd1db3e Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 18 Apr 2023 10:01:50 +0200 Subject: [PATCH 036/170] docker-compose update for current version --- docker-compose.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 6b7db1772..a6aca9888 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,17 +16,17 @@ services: SONAR_ES_BOOTSTRAP_CHECKS_DISABLE: 'true' volumes: - type: bind - source: ./java-plugin/target/ecocode-java-plugin-1.2.1-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.2.1-SNAPSHOT.jar + source: ./java-plugin/target/ecocode-java-plugin-1.2.2-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.2.2-SNAPSHOT.jar - type: bind - source: ./javascript-plugin/target/ecocode-javascript-plugin-1.2.1-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-javascript-plugin-1.2.1-SNAPSHOT.jar + source: ./javascript-plugin/target/ecocode-javascript-plugin-1.2.2-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-javascript-plugin-1.2.2-SNAPSHOT.jar - type: bind - source: ./php-plugin/target/ecocode-php-plugin-1.2.1-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.2.1-SNAPSHOT.jar + source: ./php-plugin/target/ecocode-php-plugin-1.2.2-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.2.2-SNAPSHOT.jar - type: bind - source: ./python-plugin/target/ecocode-python-plugin-1.2.1-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-python-plugin-1.2.1-SNAPSHOT.jar + source: ./python-plugin/target/ecocode-python-plugin-1.2.2-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-python-plugin-1.2.2-SNAPSHOT.jar - "extensions:/opt/sonarqube/extensions" - "logs:/opt/sonarqube/logs" - "data:/opt/sonarqube/data" From bf98814903b3c5759da6380404558a456e0a267c Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Mon, 8 May 2023 11:13:23 +0200 Subject: [PATCH 037/170] docs: update RULES.md file with rule EC404 --- RULES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/RULES.md b/RULES.md index 7ef76d27a..e157e9aa0 100644 --- a/RULES.md +++ b/RULES.md @@ -47,3 +47,4 @@ Some are applicable for different technologies. | EC28 | Optimize read file exceptions | | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | | EC5 | Usage of preparedStatement instead of Statement | SQL will only commit the query once, whereas if you used only one statement, it would commit the query every time and thus induce unnecessary calculations by the CPU and therefore superfluous energy consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | | EC27 | Usage of system.arraycopy to copy arrays | Programs spend most of the time in loops. These can be resource consuming, especially when they integrate heavy processing (IO access). Moreover, the size of the data and processing inside the loops will not allow full use of hardware mechanisms such as the cache or compiler optimization mechanisms. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | +| EC404 | Avoid list comprehension in iterations | Use generator comprehension instead of list comprehension in for loop declaration | | 🚫 | 🚫 | 🚫 | ✅ | 🚫 | From e6b1b8c451ecba198d114bf462d6da7e80af1dc5 Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Mon, 8 May 2023 11:14:35 +0200 Subject: [PATCH 038/170] refactor: update rule EC404 (code factorization + code smells correction) --- .../AvoidListComprehensionInIterations.java | 41 ++++++++++--------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java index dec37acaa..b95cd01e1 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java @@ -4,11 +4,16 @@ import org.sonar.check.Rule; import org.sonar.plugins.python.api.PythonSubscriptionCheck; import org.sonar.plugins.python.api.SubscriptionContext; -import org.sonar.plugins.python.api.tree.*; +import org.sonar.plugins.python.api.tree.Tree; +import org.sonar.plugins.python.api.tree.ForStatement; +import org.sonar.plugins.python.api.tree.Expression; +import org.sonar.plugins.python.api.tree.CallExpression; import java.util.Objects; -import static org.sonar.plugins.python.api.tree.Tree.Kind.*; +import static org.sonar.plugins.python.api.tree.Tree.Kind.LIST_COMPREHENSION; +import static org.sonar.plugins.python.api.tree.Tree.Kind.CALL_EXPR; +import static org.sonar.plugins.python.api.tree.Tree.Kind.FOR_STMT; @Rule( key = AvoidListComprehensionInIterations.RULE_KEY, @@ -37,33 +42,31 @@ private void visitIteration(SubscriptionContext context) { } else if (forTestExpression.is(CALL_EXPR)) { CallExpression callExpression = (CallExpression) forTestExpression; - switch (callExpression.callee().firstToken().value()) { - case "zip": - case "filter": - case "enumerate": - Objects.requireNonNull(callExpression.argumentList()). - arguments().forEach(e -> visitFunctionArguments(context, e.children().get(0))); - } + visitCallExpression(context, callExpression); } } - private void visitFunctionArguments(SubscriptionContext context, Tree argument) { + private void visitFunctionArgument(SubscriptionContext context, Tree argument) { if (argument.is(LIST_COMPREHENSION)) { context.addIssue(argument.firstToken(), DESCRIPTION); } else if (argument.is(CALL_EXPR)) { CallExpression callExpression = (CallExpression) argument; - switch (callExpression.callee().firstToken().value()) { - case "zip": - case "filter": - case "enumerate": - Objects.requireNonNull(callExpression.argumentList()). - arguments().forEach(e -> visitFunctionArguments(context, e.children().get(0))); - break; - - } + visitCallExpression(context, callExpression); } + } + private void visitCallExpression(SubscriptionContext context, CallExpression callExpression){ + switch (callExpression.callee().firstToken().value()) { + case "zip": + case "filter": + case "enumerate": + Objects.requireNonNull(callExpression.argumentList()). + arguments().forEach(e -> visitFunctionArgument(context, e.children().get(0))); + break; + default: + break; + } } } From e5306f609f94607919ea72661e081973531f65d0 Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Mon, 8 May 2023 11:27:36 +0200 Subject: [PATCH 039/170] docs: update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b36e9b06..68d369758 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- [#127](https://github.com/green-code-initiative/ecoCode/issues/127) Add Python rule EC404: Usage of generator comprehension instead of list comprehension in for loop declaration. + ### Changed ### Deleted From a1d203889953069769da7001b196084c0bae4d5a Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Mon, 8 May 2023 11:40:28 +0200 Subject: [PATCH 040/170] refactor: better check for function arguments, and better retrieving of function name --- .../AvoidListComprehensionInIterations.java | 41 ++++++++++++------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java index b95cd01e1..e22d73d4a 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java @@ -4,16 +4,19 @@ import org.sonar.check.Rule; import org.sonar.plugins.python.api.PythonSubscriptionCheck; import org.sonar.plugins.python.api.SubscriptionContext; -import org.sonar.plugins.python.api.tree.Tree; -import org.sonar.plugins.python.api.tree.ForStatement; +import org.sonar.plugins.python.api.symbols.Symbol; import org.sonar.plugins.python.api.tree.Expression; import org.sonar.plugins.python.api.tree.CallExpression; +import org.sonar.plugins.python.api.tree.ForStatement; +import org.sonar.plugins.python.api.tree.Tree; +import org.sonar.plugins.python.api.tree.RegularArgument; import java.util.Objects; -import static org.sonar.plugins.python.api.tree.Tree.Kind.LIST_COMPREHENSION; import static org.sonar.plugins.python.api.tree.Tree.Kind.CALL_EXPR; import static org.sonar.plugins.python.api.tree.Tree.Kind.FOR_STMT; +import static org.sonar.plugins.python.api.tree.Tree.Kind.LIST_COMPREHENSION; +import static org.sonar.plugins.python.api.tree.Tree.Kind.REGULAR_ARGUMENT; @Rule( key = AvoidListComprehensionInIterations.RULE_KEY, @@ -46,27 +49,35 @@ private void visitIteration(SubscriptionContext context) { } } - private void visitFunctionArgument(SubscriptionContext context, Tree argument) { - if (argument.is(LIST_COMPREHENSION)) { - context.addIssue(argument.firstToken(), DESCRIPTION); - - } else if (argument.is(CALL_EXPR)) { - CallExpression callExpression = (CallExpression) argument; - visitCallExpression(context, callExpression); - } - } - private void visitCallExpression(SubscriptionContext context, CallExpression callExpression){ - switch (callExpression.callee().firstToken().value()) { + switch (getFunctionNameFromCallExpression(callExpression)) { case "zip": case "filter": case "enumerate": Objects.requireNonNull(callExpression.argumentList()). - arguments().forEach(e -> visitFunctionArgument(context, e.children().get(0))); + arguments().forEach(e -> visitFunctionArgument(context, e)); break; default: break; } } + private void visitFunctionArgument(SubscriptionContext context, Tree argument) { + if (argument.is(REGULAR_ARGUMENT)) { + Expression expression = ((RegularArgument)argument).expression(); + if (expression.is(LIST_COMPREHENSION)) { + context.addIssue(expression.firstToken(), DESCRIPTION); + + } else if (expression.is(CALL_EXPR)) { + CallExpression callExpression = (CallExpression) expression; + visitCallExpression(context, callExpression); + } + } + } + + private static String getFunctionNameFromCallExpression(CallExpression callExpression) { + Symbol symbol = callExpression.calleeSymbol(); + return symbol != null && symbol.name() != null ? symbol.name() : ""; + } + } From 5146a9f1b3b134ebaa38bc67ac2a92f95feb167b Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Mon, 8 May 2023 23:29:54 +0200 Subject: [PATCH 041/170] refactor: remove useless linebreaks --- .../python/checks/AvoidListComprehensionInIterations.java | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java index e22d73d4a..8ff881836 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java @@ -32,7 +32,6 @@ public class AvoidListComprehensionInIterations extends PythonSubscriptionCheck @Override public void initialize(Context context) { context.registerSyntaxNodeConsumer(FOR_STMT, this::visitIteration); - } private void visitIteration(SubscriptionContext context) { @@ -40,9 +39,7 @@ private void visitIteration(SubscriptionContext context) { Expression forTestExpression = forStatement.testExpressions().get(0); if (forTestExpression.is(LIST_COMPREHENSION)) { - context.addIssue(forTestExpression.firstToken(), DESCRIPTION); - } else if (forTestExpression.is(CALL_EXPR)) { CallExpression callExpression = (CallExpression) forTestExpression; visitCallExpression(context, callExpression); @@ -67,7 +64,6 @@ private void visitFunctionArgument(SubscriptionContext context, Tree argument) { Expression expression = ((RegularArgument)argument).expression(); if (expression.is(LIST_COMPREHENSION)) { context.addIssue(expression.firstToken(), DESCRIPTION); - } else if (expression.is(CALL_EXPR)) { CallExpression callExpression = (CallExpression) expression; visitCallExpression(context, callExpression); @@ -75,9 +71,8 @@ private void visitFunctionArgument(SubscriptionContext context, Tree argument) { } } - private static String getFunctionNameFromCallExpression(CallExpression callExpression) { + private String getFunctionNameFromCallExpression(CallExpression callExpression) { Symbol symbol = callExpression.calleeSymbol(); return symbol != null && symbol.name() != null ? symbol.name() : ""; } - } From 7513076522101458be7dc3c2e5b31bcd2a06ca6f Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 10 May 2023 08:27:49 +0200 Subject: [PATCH 042/170] upgrade README.md with last data --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index eff1fbc1b..5ebecab8c 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,7 @@ Ready to use binaries are available [from GitHub](https://github.com/green-code- | 0.2.+ | 11 / 17 | | 1.0.+ | 11 / 17 | | 1.1.+ | 11 / 17 | +| 1.2.+ | 11 / 17 | 🤝 Contribution --------------- @@ -117,13 +118,13 @@ Any question ? We are here for you ! first, create an issue, please. Then, if no answer, contact ... -- Jules Delecour +- [Jules Delecour](https://www.linkedin.com/in/jules-delecour-498680118/) - [Geoffrey Lalloué](https://github.com/glalloue) -- Julien Hertout +- [Julien Hertout](https://www.linkedin.com/in/julien-hertout-b1175449/) - [Justin Berque](https://www.linkedin.com/in/justin-berque-444412140) - [Olivier Le Goaër](https://olegoaer.perso.univ-pau.fr) -- Maxime DUBOIS -- [David DE CARVALHO](https://www.linkedin.com/in/%E2%80%8E-%E2%80%8E-%E2%80%8E-%E2%80%8E-%E2%80%8E-david%E2%80%8E-%E2%80%8E-%E2%80%8E-%E2%80%8E-%E2%80%8E-%E2%80%8E-%E2%80%8E%E2%80%8E-%E2%80%8E-%E2%80%8E-%E2%80%8E-de-carvalho%E2%80%8E-%E2%80%8E-%E2%80%8E-%E2%80%8E-%E2%80%8E-8b395284/) +- [Maxime DUBOIS](https://www.linkedin.com/in/maxime-dubois-%F0%9F%8C%B1-649a3a3/) +- [David DE CARVALHO](https://www.linkedin.com/in/david%E2%80%8E-de-carvalho-8b395284/) 🧐 Core Team Emeriti -------------------- From f9c0e6224ddda842d8a50c4b8b6fb615208aa2ee Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 10 May 2023 08:28:49 +0200 Subject: [PATCH 043/170] upgrade to SonarQube 10.0.0 (manual checks) --- Dockerfile | 2 +- README.md | 13 +++++++------ docker-compose.yml | 2 +- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/Dockerfile b/Dockerfile index 0fd4e5340..bd5462ffb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,5 +5,5 @@ COPY . /usr/src/ecocode WORKDIR /usr/src/ecocode RUN ./tool_build.sh -FROM sonarqube:9.9-community +FROM sonarqube:10.0.0-community COPY --from=builder /usr/src/ecocode/lib/* /opt/sonarqube/extensions/plugins/ diff --git a/README.md b/README.md index 5ebecab8c..c050991eb 100644 --- a/README.md +++ b/README.md @@ -78,12 +78,13 @@ Ready to use binaries are available [from GitHub](https://github.com/green-code- 🧩 Plugins version compatibility ------------------ -| Plugins Version | SonarQube version | -|------------------|----------------------------| -| 0.1.+ | SonarQube 8.9.+ LTS to 9.3 | -| 0.2.+ | SonarQube 9.4.+ LTS to 9.9 | -| 1.0.+ | SonarQube 9.4.+ LTS to 9.9 | -| 1.1.+ | SonarQube 9.4.+ LTS to 9.9 | +| Plugins Version | SonarQube version | +|------------------|-----------------------------| +| 0.1.+ | SonarQube 8.9.+ LTS to 9.3 | +| 0.2.+ | SonarQube 9.4.+ LTS to 9.9 | +| 1.0.+ | SonarQube 9.4.+ LTS to 9.9 | +| 1.1.+ | SonarQube 9.4.+ LTS to 9.9 | +| 1.2.+ | SonarQube 9.4.+ LTS to 10.0 | ☕ Plugin Java part compatibility ------------------ diff --git a/docker-compose.yml b/docker-compose.yml index a6aca9888..32a7dc027 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,7 +1,7 @@ version: "3.3" services: sonar: - image: sonarqube:9.9-community + image: sonarqube:10.0.0-community container_name: sonar_ecocode ports: - "9000:9000" From 8870c64b1e89a95f683a933d87fcd2ea8bfaa4d8 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 10 May 2023 16:46:13 +0200 Subject: [PATCH 044/170] [ISSUE 184] upgrade component versions / clean pom.xml / upgrade code for SonarQube 10 --- java-plugin/pom.xml | 33 +---------- .../java/JavaRulesDefinition.java | 2 +- .../java/JavaPluginTest.java | 2 +- javascript-plugin/pom.xml | 30 ++-------- .../javascript/JavaScriptPluginTest.java | 2 +- php-plugin/pom.xml | 35 ----------- .../php/PhpPluginTest.java | 2 +- pom.xml | 59 +++++++++++++++---- python-plugin/pom.xml | 35 ----------- .../python/PythonPluginTest.java | 2 +- 10 files changed, 60 insertions(+), 142 deletions(-) diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index acb1b601c..773c3a0bd 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -87,40 +87,9 @@ + org.apache.maven.plugins maven-shade-plugin - - - package - - shade - - - - - commons-*:* - - META-INF/** - - - - org.*:* - - META-INF/** - org/sonar/api/batch/sensor/** - javax/annotation/** - - - - com.*:* - - META-INF/** - - - - - - org.jacoco diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java index 9b6d698d5..37a82c438 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java @@ -52,7 +52,7 @@ public class JavaRulesDefinition implements RulesDefinition { public void define(Context context) { NewRepository repository = context.createRepository(REPOSITORY_KEY, LANGUAGE).setName(NAME); - SonarRuntime sonarRuntime = SonarRuntimeImpl.forSonarQube(Version.create(9, 8), SonarQubeSide.SCANNER, SonarEdition.DEVELOPER); + SonarRuntime sonarRuntime = SonarRuntimeImpl.forSonarQube(Version.create(10, 0), SonarQubeSide.SCANNER, SonarEdition.DEVELOPER); RuleMetadataLoader ruleMetadataLoader = new RuleMetadataLoader(RESOURCE_BASE_PATH, sonarRuntime); diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java index 53eaad42e..649268421 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java @@ -43,7 +43,7 @@ private static class MockedSonarRuntime implements SonarRuntime { @Override public Version getApiVersion() { - return Version.create(9, 9); + return Version.create(10, 0); } @Override diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml index 3349c963f..ebf069c23 100644 --- a/javascript-plugin/pom.xml +++ b/javascript-plugin/pom.xml @@ -68,33 +68,13 @@ + org.apache.maven.plugins maven-shade-plugin - - - package - - shade - - - - - commons-*:* - - META-INF/** - - - - org.*:* - - META-INF/** - org/sonar/api/batch/sensor/** - - - - - - + org.apache.maven.plugins diff --git a/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java b/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java index ad50f25ec..3f8ed8f3f 100644 --- a/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java +++ b/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java @@ -19,7 +19,7 @@ private static class MockedSonarRuntime implements SonarRuntime { @Override public Version getApiVersion() { - return Version.create(9, 9); + return Version.create(10, 0); } @Override diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index 0910c07b5..3ee2639c8 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -64,41 +64,6 @@ ${java.version} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - org.apache.maven.plugins maven-dependency-plugin diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java index 3c89dab5a..b64679cbb 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java @@ -32,7 +32,7 @@ public class PhpPluginTest { @Test public void test() { - SonarRuntime sonarRuntime = SonarRuntimeImpl.forSonarQube(Version.create(9, 9), SonarQubeSide.SCANNER, SonarEdition.DEVELOPER); + SonarRuntime sonarRuntime = SonarRuntimeImpl.forSonarQube(Version.create(10, 0), SonarQubeSide.SCANNER, SonarEdition.DEVELOPER); Plugin.Context context = new PluginContextImpl.Builder().setSonarRuntime(sonarRuntime).build(); new PHPPlugin().define(context); assertThat(context.getExtensions()).hasSize(1); diff --git a/pom.xml b/pom.xml index 4f15d9b78..0ec29ab22 100644 --- a/pom.xml +++ b/pom.xml @@ -50,24 +50,24 @@ ${encoding} ${encoding} - 9.4.0.54424 - green-code-initiative https://sonarcloud.io - - 0.8.8 + 9.4.0.54424 + 10.0.0.68432 - 7.15.0.30507 - 3.19.0.10254 - 3.25.0.9077 - 9.13.0.20537 + 7.19.0.31550 + 4.3.0.11660 + 3.29.0.9684 + 10.2.0.21568 + + 2.5.0.1358 - 9.7.1.62043 - 2.1.0.1111 1.21.0.505 true 3.4.1 + + 0.8.10 5.9.1 3.23.1 @@ -195,6 +195,45 @@ org.apache.maven.plugins maven-shade-plugin ${maven-shade-plugin.version} + + + + package + + shade + + + + + commons-*:* + + META-INF/** + + + + org.*:* + + META-INF/** + org/sonar/api/batch/sensor/** + javax/annotation/** + + + + com.*:* + + META-INF/** + + + + junit:* + + META-INF/** + + + + + + org.jacoco diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index 1a239fa51..e16bdca63 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -61,41 +61,6 @@ ${java.version} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - org.apache.maven.plugins maven-dependency-plugin diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java index 03c88941b..a5ad52390 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java @@ -32,7 +32,7 @@ public class PythonPluginTest { @Test public void test() { - SonarRuntime sonarRuntime = SonarRuntimeImpl.forSonarQube(Version.create(9, 9), SonarQubeSide.SCANNER, SonarEdition.DEVELOPER); + SonarRuntime sonarRuntime = SonarRuntimeImpl.forSonarQube(Version.create(10, 0), SonarQubeSide.SCANNER, SonarEdition.DEVELOPER); Plugin.Context context = new PluginContextImpl.Builder().setSonarRuntime(sonarRuntime).build(); new PythonPlugin().define(context); assertThat(context.getExtensions()).hasSize(1); From 34e03424009ea0643d9a66c2ef1242575838b512 Mon Sep 17 00:00:00 2001 From: utarwyn Date: Sun, 14 May 2023 19:17:04 +0200 Subject: [PATCH 045/170] Update JavaScript rules --- .../l10n/javascript/rules.json | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/javascript-plugin/src/main/resources/fr/greencodeinitiative/l10n/javascript/rules.json b/javascript-plugin/src/main/resources/fr/greencodeinitiative/l10n/javascript/rules.json index 5beda43e8..e86627bb5 100644 --- a/javascript-plugin/src/main/resources/fr/greencodeinitiative/l10n/javascript/rules.json +++ b/javascript-plugin/src/main/resources/fr/greencodeinitiative/l10n/javascript/rules.json @@ -1,4 +1,28 @@ [ + { + "key": "@ecocode/avoid-high-accuracy-geolocation", + "type": "CODE_SMELL", + "name": "Avoid using high accuracy geolocation in web applications", + "description": "\n\n

Rule details

\n

This rule aims at reducing CPU consumption by telling the device to use a less accurate yet more eco friendly geolocation, when geolocation API is used.

\n

Examples

\n

Examples of non compliant code for this rule:

\n
var options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 };\nfunction success(pos) {\n  console.log(pos.coords);\n}\n\nfunction error(err) {\n  console.warn(err);\n}\n\nnavigator.geolocation.getCurrentPosition(success, error, options);\n
\n

Examples of compliant code for this rule:

\n
// enableHighAccuracy is false by default, so not declaring it is correct\nfunction success(pos) {\n  console.log(pos);\n}\nnavigator.geolocation.getCurrentPosition(success);\n
\n
var options = { enableHighAccuracy: false, timeout: 5000, maximumAge: 0 };\nfunction success(pos) {\n  console.log(pos.coords);\n}\n\nfunction error(err) {\n  console.warn(err);\n}\n\nnavigator.geolocation.getCurrentPosition(success, error, options);\n
\n
Click here to access the rule details.", + "constantDebtMinutes": 5, + "severity": "MINOR", + "tags": [ + "eco-design", + "ecocode" + ] + }, + { + "key": "@ecocode/no-import-all-from-library", + "type": "CODE_SMELL", + "name": "Should not import all from librar", + "description": "\n\n

Rule details

\n

This rule aims to reduce weight of programs by using only needed modules. Many libraries export only one module by\ndefault, but some of them are exporting ES modules or submodules. We should use them to select more precisly needed\nmodules and avoid unnecessarily overloading files weight.

\n

\"Example

\n

Example with the well-known lodash library, if you only need "isEmpty" method.

\n

Options

\n

You can externally add your own libraries to be checked.\nTo add your own libraries you need to modify your .eslintrc.js by adding the following rule configuration:

\n
module.exports = {\n  ...yourConf,\n  rules: {\n    "no-import-all-from-library": [\n      "warn",\n      {\n        notAllowedLibraries: ["some-lib"], // will check for -> import someLib from "some-lib"\n        importByNamespaceNotAllowedLibraries: ["some-other-lib"], // will check for -> import * as someOtherLib from "some-other-lib"\n      },\n    ],\n  },\n};\n
\n

Examples

\n

Examples of non-compliant code for this rule:

\n
// Example with lodash\nimport lodash from "lodash";\nimport { isEmpty } from "lodash";\nimport * as lodash from "lodash";\n\n// Example with underscore\nimport _ from "underscore";\n
\n

Examples of compliant code for this rule:

\n
// Example with lodash (uses submodules)\nimport isEmpty from "lodash/isEmpty";\nimport intersect from "lodash/intersect";\n\n// Example with underscore (uses esm modules)\nimport map from "underscore/modules/map.js";\n
\n
Click here to access the rule details.", + "constantDebtMinutes": 5, + "severity": "MINOR", + "tags": [ + "eco-design", + "ecocode" + ] + }, { "key": "@ecocode/no-multiple-access-dom-element", "type": "CODE_SMELL", From 5fcf195815e2f9ca86d5e23e9e91775a75552466 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 16 May 2023 22:01:53 +0200 Subject: [PATCH 046/170] update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b36e9b06..0bcca3e0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- process changed for development environment installation : easier to initialize locally environment (check (`INSTALL.md`)[https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment] file) + ### Deleted ## [1.2.1] - 2023-04-18 From bee566394fc58a32e9ca1aac01dd4c19c352219a Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 16 May 2023 22:02:56 +0200 Subject: [PATCH 047/170] correction link in CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bcca3e0a..89bd3cba4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- process changed for development environment installation : easier to initialize locally environment (check (`INSTALL.md`)[https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment] file) +- process changed for development environment installation : easier to initialize locally environment (check [`INSTALL.md`](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment) file) ### Deleted From 08ae84c75a32158368df19472a4cc75d60ce98f4 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 16 May 2023 22:04:12 +0200 Subject: [PATCH 048/170] improive CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 89bd3cba4..1dcc6b5fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- process changed for development environment installation : easier to initialize locally environment (check [`INSTALL.md`](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment) file) +- [#19](https://github.com/green-code-initiative/ecoCode-common/issues/19) process changed for development environment installation : easier to initialize locally environment (check [`INSTALL.md`](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment) file) ### Deleted From cc7e34c2cad0b2e070cc76b0e6731169c74b6464 Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Tue, 16 May 2023 22:36:04 +0200 Subject: [PATCH 049/170] refactor: remove duplicated test in AvoidListComprehensionInIterations python file --- .../resources/checks/AvoidListComprehensionInIterations.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/python-plugin/src/test/resources/checks/AvoidListComprehensionInIterations.py b/python-plugin/src/test/resources/checks/AvoidListComprehensionInIterations.py index 9dab94c8b..547eb5724 100644 --- a/python-plugin/src/test/resources/checks/AvoidListComprehensionInIterations.py +++ b/python-plugin/src/test/resources/checks/AvoidListComprehensionInIterations.py @@ -10,10 +10,6 @@ def non_compliant_example_zip(): for var, var_ in zip([var2 for var2 in range(1000)], [var2 for var2 in range(1000)]): # Noncompliant {{Use generator comprehension instead of list comprehension in for loop declaration}} {{Use generator comprehension instead of list comprehension in for loop declaration}} print(var) -def non_compliant_example_zip(): - for var, var_ in zip([var2 for var2 in range(1000)], [var2 for var2 in range(1000)]): # Noncompliant {{Use generator comprehension instead of list comprehension in for loop declaration}} {{Use generator comprehension instead of list comprehension in for loop declaration}} - print(var) - def non_compliant_example_enumerate_zip(): for packed_var in enumerate(zip([1, 2, 3], filter(bool, [idx % 2 for idx in range(100)]))): # Noncompliant {{Use generator comprehension instead of list comprehension in for loop declaration}} print(packed_var) @@ -36,4 +32,4 @@ def compliant_example_with_enumerate(): def compliant_example_with_zip(): for var, var2 in zip((idx for idx in range(3)), ["a", "b", "c"]): - print(var) \ No newline at end of file + print(var) From 7f050a2ee0700f662b6731bc09802e6f4f30221b Mon Sep 17 00:00:00 2001 From: Eliott Lavier <67601109+eliottlv@users.noreply.github.com> Date: Thu, 6 Apr 2023 09:59:30 +0200 Subject: [PATCH 050/170] [ISSUE 113] Use unoptimized vector images --- .../python/PythonRuleRepository.java | 8 +-- .../AvoidUnoptimizedVectorImagesCheck.java | 66 +++++++++++++++++++ .../l10n/python/rules/python/EC10.html | 47 +++++++++++++ .../python/PythonRuleRepositoryTest.java | 4 +- .../AvoidUnoptimizedVectorImagesTest.java | 12 ++++ .../checks/avoidUnoptimizedVectorImages.py | 5 ++ 6 files changed, 134 insertions(+), 8 deletions(-) create mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java create mode 100644 python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC10.html create mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesTest.java create mode 100644 python-plugin/src/test/resources/checks/avoidUnoptimizedVectorImages.py diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java index 93de44ffb..726ded00e 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java @@ -29,12 +29,7 @@ import java.util.List; import java.util.Map; -import fr.greencodeinitiative.python.checks.AvoidFullSQLRequest; -import fr.greencodeinitiative.python.checks.AvoidGettersAndSetters; -import fr.greencodeinitiative.python.checks.AvoidGlobalVariableInFunctionCheck; -import fr.greencodeinitiative.python.checks.AvoidSQLRequestInLoop; -import fr.greencodeinitiative.python.checks.AvoidTryCatchFinallyCheck; -import fr.greencodeinitiative.python.checks.NoFunctionCallWhenDeclaringForLoop; +import fr.greencodeinitiative.python.checks.*; import org.apache.commons.lang.StringUtils; import org.sonar.api.rules.RuleType; import org.sonar.api.server.rule.RulesDefinition; @@ -93,6 +88,7 @@ public List checkClasses() { AvoidGlobalVariableInFunctionCheck.class, AvoidSQLRequestInLoop.class, AvoidTryCatchFinallyCheck.class, + AvoidUnoptimizedVectorImagesCheck.class, NoFunctionCallWhenDeclaringForLoop.class, AvoidFullSQLRequest.class ); diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java new file mode 100644 index 000000000..743e7ad71 --- /dev/null +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java @@ -0,0 +1,66 @@ +package fr.greencodeinitiative.python.checks; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.sonar.check.Priority; +import org.sonar.check.Rule; +import org.sonar.plugins.python.api.PythonSubscriptionCheck; +import org.sonar.plugins.python.api.SubscriptionContext; +import org.sonar.plugins.python.api.tree.*; + +@Rule( + key = AvoidUnoptimizedVectorImagesCheck.RULE_KEY, + name = AvoidUnoptimizedVectorImagesCheck.DESCRIPTION, + description = AvoidUnoptimizedVectorImagesCheck.DESCRIPTION, + priority = Priority.MINOR, + tags = {"eco-design", "ecocode"}) +public class AvoidUnoptimizedVectorImagesCheck extends PythonSubscriptionCheck { + + public static final String RULE_KEY = "EC10"; + public static final String DESCRIPTION = "Avoid using unoptimized vector images"; + private static final Pattern COMMENT_PATTERN = Pattern.compile("()"); + private static final Pattern LAYERS_PATTERN = Pattern.compile(""); + private static final Pattern NAMESPACE_PATTERN = Pattern.compile("xmlns:(?!svg)[a-z0-9]+"); + private static final String STRING_TAG_TO_DETECT = ""; + + @Override + public void initialize(Context ctx) { + ctx.registerSyntaxNodeConsumer(Tree.Kind.STRING_ELEMENT, this::checkSVG); + } + + public void checkSVG(SubscriptionContext ctx) { + StringElement stringLiteral = (StringElement) ctx.syntaxNode(); + checkComments(stringLiteral, ctx); + checkLayers(stringLiteral, ctx); + checkNamespaces(stringLiteral, ctx); + checkMetadata(stringLiteral, ctx); + } + + private void checkComments(StringElement str, SubscriptionContext ctx) { + if (str.value().contains(AvoidUnoptimizedVectorImagesCheck.STRING_TAG_TO_DETECT) && COMMENT_PATTERN.matcher(str.value()).find()) { + ctx.addIssue(str, DESCRIPTION); + } + } + + private void checkLayers(StringElement str, SubscriptionContext ctx) { + Matcher matcher = LAYERS_PATTERN.matcher(str.value()); + int matches = 0; + while (matcher.find()) matches++; + if (str.value().contains(AvoidUnoptimizedVectorImagesCheck.STRING_TAG_TO_DETECT) && matches > 1) { + ctx.addIssue(str, DESCRIPTION); + } + } + + private void checkNamespaces(StringElement str, SubscriptionContext ctx) { + if (str.value().contains(AvoidUnoptimizedVectorImagesCheck.STRING_TAG_TO_DETECT) && NAMESPACE_PATTERN.matcher(str.value()).find()) { + ctx.addIssue(str, DESCRIPTION); + } + } + + private void checkMetadata(StringElement str, SubscriptionContext ctx) { + if (str.value().contains(AvoidUnoptimizedVectorImagesCheck.STRING_TAG_TO_DETECT) && str.value().contains("")) { + ctx.addIssue(str, DESCRIPTION); + } + } +} diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC10.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC10.html new file mode 100644 index 000000000..555e80b74 --- /dev/null +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC10.html @@ -0,0 +1,47 @@ +

SVG images generated by common drawing softwares contains unnecessary data : calc layer, metadata, namespaces and comments.

+

Noncompliant Code Example

+
+<!-- Created with Inkscape (http://www.inkscape.org/) -->
+<svg
+    width="210mm"
+    height="297mm"
+    viewBox="0 0 210 297"
+    version="1.1"
+    id="svg5"
+    inkscape:version="1.2.2 (b0a8486541, 2022-12-01)"
+    sodipodi:docname="dessin2.svg"
+    xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+    xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+    xmlns="http://www.w3.org/2000/svg"
+    xmlns:svg="http://www.w3.org/2000/svg">
+    <g
+            inkscape:label="Calque 1"
+            inkscape:groupmode="layer"
+            id="layer1">
+        <circle
+            style="fill:#ff00ff;stroke-width:0.264583"
+            id="path111"
+            cx="104.02724"
+            cy="152.19028"
+            r="73.177132" />
+    </g>
+</svg>
+
+

Compliant Solution

+
+<svg
+    width="210mm"
+    height="297mm"
+    viewBox="0 0 210 297"
+    xmlns="http://www.w3.org/2000/svg"
+    xmlns:svg="http://www.w3.org/2000/svg">
+    <g>
+        <circle
+            style="fill:#ff00ff;stroke-width:0.264583"
+            id="path111"
+            cx="104.02724"
+            cy="152.19028"
+            r="73.177132" />
+    </g>
+</svg>
+
diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java index 101ff2841..f724dd805 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java @@ -44,8 +44,8 @@ public void init() { public void test() { assertThat(pythonRuleRepository.repositoryKey()).isEqualTo(PythonRuleRepository.REPOSITORY_KEY); assertThat(context.repositories()).hasSize(1).extracting("key").containsExactly(pythonRuleRepository.repositoryKey()); - assertThat(context.repositories().get(0).rules()).hasSize(6); - assertThat(pythonRuleRepository.checkClasses()).hasSize(6); + assertThat(context.repositories().get(0).rules()).hasSize(7); + assertThat(pythonRuleRepository.checkClasses()).hasSize(7); } diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesTest.java new file mode 100644 index 000000000..09a738575 --- /dev/null +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesTest.java @@ -0,0 +1,12 @@ +package fr.greencodeinitiative.python.checks; + +import org.junit.Test; +import org.sonar.python.checks.utils.PythonCheckVerifier; + +public class AvoidUnoptimizedVectorImagesTest { + + @Test + public void test() { + PythonCheckVerifier.verify("src/test/resources/checks/avoidUnoptimizedVectorImages.py", new AvoidUnoptimizedVectorImagesCheck()); + } +} diff --git a/python-plugin/src/test/resources/checks/avoidUnoptimizedVectorImages.py b/python-plugin/src/test/resources/checks/avoidUnoptimizedVectorImages.py new file mode 100644 index 000000000..9893da59c --- /dev/null +++ b/python-plugin/src/test/resources/checks/avoidUnoptimizedVectorImages.py @@ -0,0 +1,5 @@ +image0 = """""" +image1 = """""" # Noncompliant {{Avoid using unoptimized vector images}} +image2 = "" # Noncompliant {{Avoid using unoptimized vector images}} +image3 = "......" # Noncompliant {{Avoid using unoptimized vector images}} +image4 = "" # Noncompliant {{Avoid using unoptimized vector images}} From aca28d78ed7df19cbbc9c948d6851dc3cdeb13c1 Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Tue, 16 May 2023 23:43:54 +0200 Subject: [PATCH 051/170] refactor: replace bug tag by performance for AvoidListComprehensionInIterations python rule --- .../python/checks/AvoidListComprehensionInIterations.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java index 8ff881836..5cb64346d 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java @@ -23,7 +23,7 @@ name = AvoidListComprehensionInIterations.DESCRIPTION, description = AvoidListComprehensionInIterations.DESCRIPTION, priority = Priority.MINOR, - tags = {"bug", "eco-design", "ecocode"}) + tags = {"eco-design", "ecocode", "performance"}) public class AvoidListComprehensionInIterations extends PythonSubscriptionCheck { public static final String RULE_KEY = "EC404"; From 1ccc014aeda0ca8733eb8057a91b9de899fc666e Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 17 May 2023 00:09:10 +0200 Subject: [PATCH 052/170] [ISSUE 113] review notes modifications --- CHANGELOG.md | 2 ++ RULES.md | 2 +- .../AvoidUnoptimizedVectorImagesCheck.java | 26 +++++++++++++++---- 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dcc6b5fc..82b41f6f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- [#113](https://github.com/green-code-initiative/ecoCode/issues/113) new PYTHON rule : Use unoptimized vector images + ### Changed - [#19](https://github.com/green-code-initiative/ecoCode-common/issues/19) process changed for development environment installation : easier to initialize locally environment (check [`INSTALL.md`](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment) file) diff --git a/RULES.md b/RULES.md index 7ef76d27a..9222b77b5 100644 --- a/RULES.md +++ b/RULES.md @@ -18,7 +18,7 @@ Some are applicable for different technologies. | | Non-standard fonts used | Prefer standard fonts, as they are already present on the user's computer, so they do not need to download them. This saves bandwidth, while speeding up the display of the site. | [cnumr best practices (3rd edition) BP_029](https://github.com/cnumr/best-practices/blob/main/chapters/BP_029_fr.md) | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | | | Non-outsourced CSS and Javascript | If you include CSS or JavaScript code in the body of the HTML file, while the HTML file is used by several pages (or even the entire site), this code must be transferred for each page requested by the user, which increases the volume of data transmitted. | [cnumr best practices (3rd edition) BP_032](https://github.com/cnumr/best-practices/blob/main/chapters/BP_032_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | | | Resize images browser-side | Do not resize images using the HEIGHT and WIDTH attributes of the HTML code. This approach requires transferring these images to their original size, wasting bandwidth and CPU cycles. | [cnumr best practices (3rd edition) BP_034](https://github.com/cnumr/best-practices/blob/main/chapters/BP_034_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | -| EC10 | Use unoptimized vector images | Less heavy SVG images using less bandwidth | [cnumr best practices (3rd edition) BP_036](https://github.com/cnumr/best-practices/blob/main/chapters/BP_036_fr.md) | 🚧 | 🚀 | 🚀 | 🚧 | 🚀 | +| EC10 | Use unoptimized vector images | Less heavy SVG images using less bandwidth | [cnumr best practices (3rd edition) BP_036](https://github.com/cnumr/best-practices/blob/main/chapters/BP_036_fr.md) | 🚧 | 🚀 | 🚀 | ✅ | 🚀 | | | Using too many CSS/javascript animations | JavaScript/CSS animations can be very expensive in terms of CPU cycles and memory consumption. | [cnumr best practices (3rd edition) BP_039](https://github.com/cnumr/best-practices/blob/main/chapters/BP_039_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | | | Modify the DOM when traversing it | Modifying the DOM (Document Object Model) as you traverse it can lead to situations where the loop becomes very resource-intensive, especially CPU cycles. | [cnumr best practices (3rd edition) BP_041](https://github.com/cnumr/best-practices/blob/main/chapters/BP_041_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | | | Edit DOM elements to make it invisible | When an element of the Document Object Model (DOM) needs to be modified by several properties, each change in style or content will generate a repaint or reflow. | [cnumr best practices (3rd edition) BP_042](https://github.com/cnumr/best-practices/blob/main/chapters/BP_042_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java index 743e7ad71..d729a091f 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java @@ -29,7 +29,7 @@ public void initialize(Context ctx) { ctx.registerSyntaxNodeConsumer(Tree.Kind.STRING_ELEMENT, this::checkSVG); } - public void checkSVG(SubscriptionContext ctx) { + private void checkSVG(SubscriptionContext ctx) { StringElement stringLiteral = (StringElement) ctx.syntaxNode(); checkComments(stringLiteral, ctx); checkLayers(stringLiteral, ctx); @@ -38,29 +38,45 @@ public void checkSVG(SubscriptionContext ctx) { } private void checkComments(StringElement str, SubscriptionContext ctx) { - if (str.value().contains(AvoidUnoptimizedVectorImagesCheck.STRING_TAG_TO_DETECT) && COMMENT_PATTERN.matcher(str.value()).find()) { + if (isSvgTagNotDetected(str)) + return; + + if (COMMENT_PATTERN.matcher(str.value()).find()) { ctx.addIssue(str, DESCRIPTION); } } private void checkLayers(StringElement str, SubscriptionContext ctx) { + if (isSvgTagNotDetected(str)) + return; + Matcher matcher = LAYERS_PATTERN.matcher(str.value()); int matches = 0; while (matcher.find()) matches++; - if (str.value().contains(AvoidUnoptimizedVectorImagesCheck.STRING_TAG_TO_DETECT) && matches > 1) { + if (matches > 1) { ctx.addIssue(str, DESCRIPTION); } } private void checkNamespaces(StringElement str, SubscriptionContext ctx) { - if (str.value().contains(AvoidUnoptimizedVectorImagesCheck.STRING_TAG_TO_DETECT) && NAMESPACE_PATTERN.matcher(str.value()).find()) { + if (isSvgTagNotDetected(str)) + return; + + if (NAMESPACE_PATTERN.matcher(str.value()).find()) { ctx.addIssue(str, DESCRIPTION); } } private void checkMetadata(StringElement str, SubscriptionContext ctx) { - if (str.value().contains(AvoidUnoptimizedVectorImagesCheck.STRING_TAG_TO_DETECT) && str.value().contains("")) { + if (isSvgTagNotDetected(str)) + return; + + if (str.value().contains("")) { ctx.addIssue(str, DESCRIPTION); } } + + private boolean isSvgTagNotDetected(StringElement str) { + return !str.value().contains(AvoidUnoptimizedVectorImagesCheck.STRING_TAG_TO_DETECT); + } } From 22aade66932610b1662585cb2874686d5000c9bd Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 17 May 2023 08:52:35 +0200 Subject: [PATCH 053/170] [ISSUE 158] technical optimizations --- .../checks/AvoidUnoptimizedVectorImagesCheck.java | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java index d729a091f..5819eeec0 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java @@ -19,10 +19,7 @@ public class AvoidUnoptimizedVectorImagesCheck extends PythonSubscriptionCheck { public static final String RULE_KEY = "EC10"; public static final String DESCRIPTION = "Avoid using unoptimized vector images"; - private static final Pattern COMMENT_PATTERN = Pattern.compile("()"); private static final Pattern LAYERS_PATTERN = Pattern.compile(""); - private static final Pattern NAMESPACE_PATTERN = Pattern.compile("xmlns:(?!svg)[a-z0-9]+"); - private static final String STRING_TAG_TO_DETECT = ""; @Override public void initialize(Context ctx) { @@ -41,7 +38,7 @@ private void checkComments(StringElement str, SubscriptionContext ctx) { if (isSvgTagNotDetected(str)) return; - if (COMMENT_PATTERN.matcher(str.value()).find()) { + if (str.value().contains("")) { ctx.addIssue(str, DESCRIPTION); } } @@ -53,7 +50,7 @@ private void checkLayers(StringElement str, SubscriptionContext ctx) { Matcher matcher = LAYERS_PATTERN.matcher(str.value()); int matches = 0; while (matcher.find()) matches++; - if (matches > 1) { + if (matches > 1) { // if at least 2 finds, create an issue ctx.addIssue(str, DESCRIPTION); } } @@ -62,7 +59,7 @@ private void checkNamespaces(StringElement str, SubscriptionContext ctx) { if (isSvgTagNotDetected(str)) return; - if (NAMESPACE_PATTERN.matcher(str.value()).find()) { + if (str.value().contains("xmlns:") && !str.value().contains("xmlns:svg=")) { ctx.addIssue(str, DESCRIPTION); } } @@ -77,6 +74,6 @@ private void checkMetadata(StringElement str, SubscriptionContext ctx) { } private boolean isSvgTagNotDetected(StringElement str) { - return !str.value().contains(AvoidUnoptimizedVectorImagesCheck.STRING_TAG_TO_DETECT); + return !str.value().contains(""); } } From c94e575a169ffcbea4e2f8689c3c0c538c6fb2fd Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 17 May 2023 09:03:36 +0200 Subject: [PATCH 054/170] [ISSUE 113] correction tests with merge from main --- .../greencodeinitiative/python/PythonRuleRepositoryTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java index f724dd805..3562dc92d 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java @@ -44,8 +44,8 @@ public void init() { public void test() { assertThat(pythonRuleRepository.repositoryKey()).isEqualTo(PythonRuleRepository.REPOSITORY_KEY); assertThat(context.repositories()).hasSize(1).extracting("key").containsExactly(pythonRuleRepository.repositoryKey()); - assertThat(context.repositories().get(0).rules()).hasSize(7); - assertThat(pythonRuleRepository.checkClasses()).hasSize(7); + assertThat(context.repositories().get(0).rules()).hasSize(8); + assertThat(pythonRuleRepository.checkClasses()).hasSize(8); } From 2c91015912c33e449a3e9bd9a883e104e8fe9ba6 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sat, 20 May 2023 10:50:49 +0200 Subject: [PATCH 055/170] [PR 156] corrections from review notes --- CHANGELOG.md | 1 + RULES.md | 1 + .../python/checks/DetectUnoptimizedImageFormat.java | 2 +- .../python/checks/DetectUnoptimizedImageFormatTest.java | 2 +- ...plient.py => detectUnoptimizedImageFormatCompliant.py} | 8 ++++---- 5 files changed, 8 insertions(+), 6 deletions(-) rename python-plugin/src/test/resources/checks/{detectUnoptimizedImageFormatComplient.py => detectUnoptimizedImageFormatCompliant.py} (61%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24cc3c0de..f7cdf3969 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#113](https://github.com/green-code-initiative/ecoCode/issues/113) new PYTHON rule : Use unoptimized vector images - [#127](https://github.com/green-code-initiative/ecoCode/issues/127) Add Python rule EC404: Usage of generator comprehension instead of list comprehension in for loop declaration +- [#156](https://github.com/green-code-initiative/ecoCode/issues/127) Add Python rule EC404: Usage of generator comprehension instead of list comprehension in for loop declaration ### Changed diff --git a/RULES.md b/RULES.md index dbbc7871e..1837f959c 100644 --- a/RULES.md +++ b/RULES.md @@ -48,3 +48,4 @@ Some are applicable for different technologies. | EC5 | Usage of preparedStatement instead of Statement | SQL will only commit the query once, whereas if you used only one statement, it would commit the query every time and thus induce unnecessary calculations by the CPU and therefore superfluous energy consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | | EC27 | Usage of system.arraycopy to copy arrays | Programs spend most of the time in loops. These can be resource consuming, especially when they integrate heavy processing (IO access). Moreover, the size of the data and processing inside the loops will not allow full use of hardware mechanisms such as the cache or compiler optimization mechanisms. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | | EC404 | Avoid list comprehension in iterations | Use generator comprehension instead of list comprehension in for loop declaration | | 🚫 | 🚫 | 🚫 | ✅ | 🚫 | +| EC203 | Detect unoptimized file formats | When it is possible, to use svg format image over other image format | | 🚀 | 🚀 | 🚀 | ✅ | 🚀 | diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java index c680040da..5cd3c48c7 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java @@ -15,7 +15,7 @@ name = DetectUnoptimizedImageFormat.MESSAGERULE, description = DetectUnoptimizedImageFormat.MESSAGEERROR, priority = Priority.MINOR, - tags = {"bug", "eco-design", "ecocode"}) + tags = {"eco-design", "ecocode", "performance", "user-experience"}) public class DetectUnoptimizedImageFormat extends PythonSubscriptionCheck { protected static final String RULE_KEY = "EC203"; diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java index a65679236..7c735f59f 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java @@ -8,6 +8,6 @@ public class DetectUnoptimizedImageFormatTest { @Test public void test() { PythonCheckVerifier.verify("src/test/resources/checks/detectUnoptimizedImageFormat.py", new DetectUnoptimizedImageFormat()); - PythonCheckVerifier.verifyNoIssue("src/test/resources/checks/detectUnoptimizedImageFormatComplient.py", new DetectUnoptimizedImageFormat()); + PythonCheckVerifier.verifyNoIssue("src/test/resources/checks/detectUnoptimizedImageFormatCompliant.py", new DetectUnoptimizedImageFormat()); } } diff --git a/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatComplient.py b/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatCompliant.py similarity index 61% rename from python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatComplient.py rename to python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatCompliant.py index d05486a16..886c41a3e 100644 --- a/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatComplient.py +++ b/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatCompliant.py @@ -5,13 +5,13 @@ def testImage(image) : def testImageFormat2() : - img_svg = "test/image.svg" # Complient + img_svg = "test/image.svg" # Compliant - image_format = testImage("image.svg") # Complient + image_format = testImage("image.svg") # Compliant - image_svg_html = ('' + # Complient + image_svg_html = ('' + # Compliant '' + '') - return ('' # Complient + return ('' # Compliant + '' ) \ No newline at end of file From de95f4fc3e816d976b3fd0e184c77c4d1ba02628 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sat, 20 May 2023 11:21:00 +0200 Subject: [PATCH 056/170] [Rule 203] correction CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7cdf3969..cb03809f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#113](https://github.com/green-code-initiative/ecoCode/issues/113) new PYTHON rule : Use unoptimized vector images - [#127](https://github.com/green-code-initiative/ecoCode/issues/127) Add Python rule EC404: Usage of generator comprehension instead of list comprehension in for loop declaration -- [#156](https://github.com/green-code-initiative/ecoCode/issues/127) Add Python rule EC404: Usage of generator comprehension instead of list comprehension in for loop declaration +- [#192](https://github.com/green-code-initiative/ecoCode/pull/192) Add Python rule EC203: Detect unoptimized file formats ### Changed From d184350748ff508352369bcc0293ea6d6e1ecc44 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Mon, 22 May 2023 17:01:03 +0200 Subject: [PATCH 057/170] [Rule 203] correction files format --- .../src/test/resources/checks/avoidFullSQLRequest.py | 2 -- .../src/test/resources/checks/avoidGettersAndSetters.py | 2 +- .../src/test/resources/checks/avoidTryCatchFinallyCheck.py | 2 +- .../src/test/resources/checks/detectUnoptimizedImageFormat.py | 2 +- .../resources/checks/detectUnoptimizedImageFormatCompliant.py | 2 +- .../resources/checks/noFunctionCallWhenDeclaringForLoop.py | 4 +--- 6 files changed, 5 insertions(+), 9 deletions(-) diff --git a/python-plugin/src/test/resources/checks/avoidFullSQLRequest.py b/python-plugin/src/test/resources/checks/avoidFullSQLRequest.py index 217cb6c9a..66c6adb4c 100644 --- a/python-plugin/src/test/resources/checks/avoidFullSQLRequest.py +++ b/python-plugin/src/test/resources/checks/avoidFullSQLRequest.py @@ -8,5 +8,3 @@ def displayMessage(argument1): requestCompiliant = ' SeLeCt user FrOm myTable' displayMessage(requestNonCompiliant) displayMessage(requestCompiliant) - - diff --git a/python-plugin/src/test/resources/checks/avoidGettersAndSetters.py b/python-plugin/src/test/resources/checks/avoidGettersAndSetters.py index fd72053ad..538e79a79 100644 --- a/python-plugin/src/test/resources/checks/avoidGettersAndSetters.py +++ b/python-plugin/src/test/resources/checks/avoidGettersAndSetters.py @@ -23,4 +23,4 @@ def is_major(self): return self.age >= 18 def get_weight(self): # Noncompliant {{Avoid creating getter and setter methods in classes}} - return self.weight \ No newline at end of file + return self.weight diff --git a/python-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck.py b/python-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck.py index 1e24bb491..cbd081e0e 100644 --- a/python-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck.py +++ b/python-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck.py @@ -26,4 +26,4 @@ def boo(): if os.path.isfile(path): fh = open(path, 'r') print(fh.read()) - fh.close \ No newline at end of file + fh.close diff --git a/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormat.py b/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormat.py index 33e2145e9..37ddac218 100644 --- a/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormat.py +++ b/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormat.py @@ -33,4 +33,4 @@ def testImageFormat2() : + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' ) \ No newline at end of file + + '' ) diff --git a/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatCompliant.py b/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatCompliant.py index 886c41a3e..205f125e7 100644 --- a/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatCompliant.py +++ b/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatCompliant.py @@ -14,4 +14,4 @@ def testImageFormat2() : '') return ('' # Compliant - + '' ) \ No newline at end of file + + '' ) diff --git a/python-plugin/src/test/resources/checks/noFunctionCallWhenDeclaringForLoop.py b/python-plugin/src/test/resources/checks/noFunctionCallWhenDeclaringForLoop.py index a3755d3e3..97cb01e63 100644 --- a/python-plugin/src/test/resources/checks/noFunctionCallWhenDeclaringForLoop.py +++ b/python-plugin/src/test/resources/checks/noFunctionCallWhenDeclaringForLoop.py @@ -6,6 +6,4 @@ def my_function(): my_function() pass - - -my_function() \ No newline at end of file +my_function() From 5f1af3c829a6eebf8c8add0f53035c67a80ec75c Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Mon, 29 May 2023 10:15:37 +0200 Subject: [PATCH 058/170] refactor: update typos in python rules html descriptions --- .../fr/greencodeinitiative/l10n/python/rules/python/EC10.html | 2 +- .../greencodeinitiative/l10n/python/rules/python/EC203.html | 2 +- .../fr/greencodeinitiative/l10n/python/rules/python/EC34.html | 4 ++-- .../fr/greencodeinitiative/l10n/python/rules/python/EC69.html | 2 +- .../fr/greencodeinitiative/l10n/python/rules/python/EC7.html | 2 +- .../fr/greencodeinitiative/l10n/python/rules/python/EC72.html | 2 +- .../fr/greencodeinitiative/l10n/python/rules/python/EC74.html | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC10.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC10.html index 555e80b74..131ab21f8 100644 --- a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC10.html +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC10.html @@ -1,4 +1,4 @@ -

SVG images generated by common drawing softwares contains unnecessary data : calc layer, metadata, namespaces and comments.

+

SVG images generated by common drawing softwares contains unnecessary data: calc layer, metadata, namespaces and comments.

Noncompliant Code Example

 <!-- Created with Inkscape (http://www.inkscape.org/) -->
diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html
index 65516edfc..7f9e458fd 100644
--- a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html
+++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html
@@ -7,7 +7,7 @@
     
  • You image need to be responsive and scale without lack of quality.
  • -

    Some advantages of using SVG : +

    Some advantages of using SVG:

    • SVGs are scalable and will render pixel-perfect at any resolution whereas JPEGs, PNGs and GIFs will not.
    • SVGs are vector images and therefore are usually much smaller in file-size than bitmap-based images.
    • diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC34.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC34.html index e72e14b5b..d90cacc9e 100644 --- a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC34.html +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC34.html @@ -1,5 +1,5 @@ -

      Inside complex code parts (for exemple multiple loops, complex data constructions...), avoid using try...catch...finally. -

      When an exception is thrown, a variable (the exception itself) is created in a catch block and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.

      +

      Inside complex code parts (for example multiple loops, complex data constructions...), avoid using try...catch...finally. +

      When an exception is thrown, a variable (the exception itself) is created in a catch block, and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.

      Noncompliant Code Example

      diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC69.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC69.html
      index 6d2b10475..2c3c64ff1 100644
      --- a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC69.html
      +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC69.html
      @@ -1,4 +1,4 @@
      -

      Do not call a function when declaring a for-type loop in order to avoid function calls each iterations. It saves CPU cycles.

      +

      Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.

      Noncompliant Code Example

       for i in my_function():  # Noncompliant
      diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC7.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC7.html
      index 181906af2..dba3dd847 100644
      --- a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC7.html
      +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC7.html
      @@ -1,4 +1,4 @@
      -

      Avoid Getters and Setters in class, It increase unless RAM memory usage.

      +

      Avoid using getters and setters in a class, as they increase unnecessary RAM memory usage.

      Noncompliant Code Example

       class Client():
      diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC72.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC72.html
      index 837f0493d..2323c02f5 100644
      --- a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC72.html
      +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC72.html
      @@ -1,4 +1,4 @@
      -

      Executing SQL queries in loop induced unnecessary calculation by the cpu, RAM usage and network transfert.

      +

      Executing SQL queries in loop induced unnecessary calculation by the cpu, RAM usage and network transfer.

      Noncompliant Code Example

           def foo():
      diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC74.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC74.html
      index 8d977de29..a18770333 100644
      --- a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC74.html
      +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC74.html
      @@ -1,4 +1,4 @@
      -

      Databases servers have to solves fileds regarding to schema. Knowing and using the schema save CPU cycles and network transfer.

      +

      Database servers have to resolve issues regarding schema fields. Knowing and using the schema save CPU cycles and network transfer.

      Noncompliant Code Example

           public void foo() {
      
      From 1d6f7333097e8a0144b4adf8db32f6142bff7b23 Mon Sep 17 00:00:00 2001
      From: Aghiles Azzoug 
      Date: Mon, 29 May 2023 10:15:53 +0200
      Subject: [PATCH 059/170] refactor: update tags in python rules
      
      ---
       .../greencodeinitiative/python/checks/AvoidFullSQLRequest.java  | 2 +-
       .../python/checks/AvoidGettersAndSetters.java                   | 2 +-
       .../python/checks/AvoidGlobalVariableInFunctionCheck.java       | 2 +-
       .../python/checks/AvoidSQLRequestInLoop.java                    | 2 +-
       .../python/checks/AvoidTryCatchFinallyCheck.java                | 2 +-
       .../python/checks/NoFunctionCallWhenDeclaringForLoop.java       | 2 +-
       6 files changed, 6 insertions(+), 6 deletions(-)
      
      diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java
      index 39e700245..413d2b036 100644
      --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java
      +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java
      @@ -21,7 +21,7 @@
               name = AvoidFullSQLRequest.MESSAGERULE,
               description = AvoidFullSQLRequest.MESSAGERULE,
               priority = Priority.MINOR,
      -        tags = {"bug", "eco-design", "ecocode"})
      +        tags = {"sql", "eco-design", "ecocode"})
       @DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "S74")
       public class AvoidFullSQLRequest extends PythonSubscriptionCheck {
       
      diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSetters.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSetters.java
      index b3aeccde1..fc1dddca4 100644
      --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSetters.java
      +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSetters.java
      @@ -23,7 +23,7 @@
               name = AvoidGettersAndSetters.DESCRIPTION,
               description = AvoidGettersAndSetters.DESCRIPTION,
               priority = Priority.MINOR,
      -        tags = {"bug", "eco-design", "ecocode"})
      +        tags = {"convention", "eco-design", "ecocode"})
       @DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "D7")
       public class AvoidGettersAndSetters extends PythonSubscriptionCheck {
       
      diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheck.java
      index ef712ec35..ab4302bbd 100644
      --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheck.java
      +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheck.java
      @@ -67,7 +67,7 @@
               name = "Do not call global variables directly inside functions",
               description = AvoidGlobalVariableInFunctionCheck.DESCRIPTION,
               priority = Priority.MINOR,
      -        tags = {"bug", "eco-design", "ecocode"})
      +        tags = {"performance", "eco-design", "ecocode"})
       @DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "D4")
       public class AvoidGlobalVariableInFunctionCheck extends PythonSubscriptionCheck {
       
      diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoop.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoop.java
      index 97877cf22..7a7c1187e 100644
      --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoop.java
      +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoop.java
      @@ -25,7 +25,7 @@
               name = "Avoid SQL request in loop",
               description = AvoidSQLRequestInLoop.MESSAGE_RULE,
               priority = Priority.MINOR,
      -        tags = {"bug", "eco-design", "ecocode"})
      +        tags = {"sql", "performance", "eco-design", "ecocode"})
       @DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "S72")
       public class AvoidSQLRequestInLoop extends PythonSubscriptionCheck {
       
      diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java
      index 70197a1e3..43ae16492 100644
      --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java
      +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java
      @@ -13,7 +13,7 @@
               name = "Avoid using try-catch statement",
               description = AvoidTryCatchFinallyCheck.DESCRIPTION,
               priority = Priority.MINOR,
      -        tags = {"bug", "eco-design", "ecocode"})
      +        tags = {"error-handling", "performance", "eco-design", "ecocode"})
       @DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "S34")
       public class AvoidTryCatchFinallyCheck extends PythonSubscriptionCheck {
       
      diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoop.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoop.java
      index 906a43253..5c7e09f05 100644
      --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoop.java
      +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoop.java
      @@ -12,7 +12,7 @@
               name = NoFunctionCallWhenDeclaringForLoop.DESCRIPTION,
               description = NoFunctionCallWhenDeclaringForLoop.DESCRIPTION,
               priority = Priority.MINOR,
      -        tags = {"bug", "eco-design", "ecocode"})
      +        tags = {"performance", "eco-design", "ecocode"})
       @DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "S69")
       public class NoFunctionCallWhenDeclaringForLoop extends PythonSubscriptionCheck {
       
      
      From 95c68b328cef8819e6ce1bb8401bd7584ed012b3 Mon Sep 17 00:00:00 2001
      From: Aghiles Azzoug 
      Date: Mon, 29 May 2023 10:22:35 +0200
      Subject: [PATCH 060/170] refactor: add performance tag for AvoidFullSQLRequest
       python rule
      
      ---
       .../greencodeinitiative/python/checks/AvoidFullSQLRequest.java  | 2 +-
       1 file changed, 1 insertion(+), 1 deletion(-)
      
      diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java
      index 413d2b036..77c5f43be 100644
      --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java
      +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java
      @@ -21,7 +21,7 @@
               name = AvoidFullSQLRequest.MESSAGERULE,
               description = AvoidFullSQLRequest.MESSAGERULE,
               priority = Priority.MINOR,
      -        tags = {"sql", "eco-design", "ecocode"})
      +        tags = {"sql", "performance", "eco-design", "ecocode"})
       @DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "S74")
       public class AvoidFullSQLRequest extends PythonSubscriptionCheck {
       
      
      From 3d155089c9752ab40511fe74405097b0551d180b Mon Sep 17 00:00:00 2001
      From: Aghiles Azzoug 
      Date: Mon, 29 May 2023 11:10:14 +0200
      Subject: [PATCH 061/170] refactor: update typos in java rules html
       descriptions
      
      ---
       .../fr/greencodeinitiative/l10n/java/rules/java/EC72.html       | 2 +-
       .../fr/greencodeinitiative/l10n/java/rules/java/EC77.html       | 2 +-
       2 files changed, 2 insertions(+), 2 deletions(-)
      
      diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC72.html b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC72.html
      index 4bb67e113..7c6588afb 100644
      --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC72.html
      +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC72.html
      @@ -1,4 +1,4 @@
      -

      Executing SQL queries in loop induced unnecessary calculation by the cpu, RAM usage and network transfert.

      +

      Executing SQL queries in loop induced unnecessary calculation by the cpu, RAM usage and network transfer.

      Noncompliant Code Example

           public void foo() {
      diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC77.html b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC77.html
      index 8de04cef2..f0aed4f4f 100644
      --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC77.html
      +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC77.html
      @@ -1,6 +1,6 @@
       

      Avoid using Pattern.compile() in a non-static context. - This operation requires a non negligible amount of computational power, Using a single match saves CPU cycles and RAM consumption. + This operation requires a significant amount of computational power, Using a single match saves CPU cycles and RAM consumption.

      Noncompliant Code Example

      From 3f343d8f6b2454573574d26044bb942d2315c5d2 Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Mon, 29 May 2023 11:14:17 +0200 Subject: [PATCH 062/170] refactor: update tags for java rules --- .../fr/greencodeinitiative/java/checks/ArrayCopyCheck.java | 2 +- .../java/checks/AvoidConcatenateStringsInLoop.java | 2 +- .../greencodeinitiative/java/checks/AvoidFullSQLRequest.java | 2 +- .../java/checks/AvoidGettingSizeCollectionInLoop.java | 2 +- .../java/checks/AvoidMultipleIfElseStatement.java | 2 +- .../java/checks/AvoidRegexPatternNotStatic.java | 2 +- .../java/checks/AvoidSQLRequestInLoop.java | 2 +- .../java/checks/AvoidSetConstantInBatchUpdate.java | 2 +- .../java/checks/AvoidSpringRepositoryCallInLoopCheck.java | 2 +- .../java/checks/AvoidStatementForDMLQueries.java | 2 +- .../java/checks/AvoidUsageOfStaticCollections.java | 2 +- .../java/checks/AvoidUsingGlobalVariablesCheck.java | 2 +- .../java/checks/FreeResourcesOfAutoCloseableInterface.java | 2 +- .../fr/greencodeinitiative/java/checks/IncrementCheck.java | 2 +- .../java/checks/InitializeBufferWithAppropriateSize.java | 2 +- .../java/checks/NoFunctionCallWhenDeclaringForLoop.java | 4 ++-- .../java/checks/OptimizeReadFileExceptions.java | 2 +- .../java/checks/UnnecessarilyAssignValuesToVariables.java | 4 ++-- .../fr/greencodeinitiative/java/checks/UseCorrectForLoop.java | 2 +- 19 files changed, 21 insertions(+), 21 deletions(-) diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java index 409303d70..5abd5201e 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java @@ -41,7 +41,7 @@ name = "Developpement", description = ArrayCopyCheck.MESSAGERULE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GRPS0027") public class ArrayCopyCheck extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java index d95335862..9b203f3fa 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java @@ -20,7 +20,7 @@ name = "Developpement", description = AvoidConcatenateStringsInLoop.MESSAGE_RULE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S75") public class AvoidConcatenateStringsInLoop extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java index c73516662..2913e970e 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java @@ -19,7 +19,7 @@ name = "Developpement", description = AvoidFullSQLRequest.MESSAGERULE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "sql", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S74") public class AvoidFullSQLRequest extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java index 7317617c0..9f70e0ede 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java @@ -22,7 +22,7 @@ name = "Developpement", description = AvoidGettingSizeCollectionInLoop.MESSAGERULE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GSCIL") public class AvoidGettingSizeCollectionInLoop extends IssuableSubscriptionVisitor { protected static final String MESSAGERULE = "Avoid getting the size of the collection in the loop"; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java index 5b584c342..64a8fa037 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java @@ -16,7 +16,7 @@ name = "Developpement", description = AvoidMultipleIfElseStatement.RULE_MESSAGE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "AMIES") public class AvoidMultipleIfElseStatement extends IssuableSubscriptionVisitor { protected static final String RULE_MESSAGE = "Using a switch statement instead of multiple if-else if possible"; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java index 1020168d8..6968e4e4e 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java @@ -21,7 +21,7 @@ name = "Developpement", description = AvoidRegexPatternNotStatic.MESSAGE_RULE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "regex", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S77") public class AvoidRegexPatternNotStatic extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java index efea9cce8..4acbaaf55 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java @@ -15,7 +15,7 @@ import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; @Rule(key = "EC72", name = "Developpement", description = AvoidSQLRequestInLoop.MESSAGERULE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "sql", "spring", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S72") public class AvoidSQLRequestInLoop extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java index 21f332e27..0a59633f8 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java @@ -24,7 +24,7 @@ @Rule(key = "EC78", name = "Developpement", description = AvoidSetConstantInBatchUpdate.MESSAGERULE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S78") public class AvoidSetConstantInBatchUpdate extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java index 2322acfaf..5730b69d9 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java @@ -16,7 +16,7 @@ name = "Developpement", description = AvoidSpringRepositoryCallInLoopCheck.RULE_MESSAGE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "spring", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GRC1") public class AvoidSpringRepositoryCallInLoopCheck extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java index f273ae707..efd76ca31 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java @@ -14,7 +14,7 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC5") +@Rule(key = "EC5", tags={"performance", "sql", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "SDMLQ1") public class AvoidStatementForDMLQueries extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java index 0dc3ce960..c75490de7 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java @@ -19,7 +19,7 @@ name = "Developpement", description = AvoidUsageOfStaticCollections.MESSAGE_RULE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"cwe", "leak", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S76") public class AvoidUsageOfStaticCollections extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java index 1e86ba874..e2f08c522 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java @@ -17,7 +17,7 @@ name = "Developpement", description = "

      Prefer local variables to globals

      ", priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "D4") public class AvoidUsingGlobalVariablesCheck extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java index d36cc9805..0cacf32d0 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java @@ -24,7 +24,7 @@ name = "Developpement", description = FreeResourcesOfAutoCloseableInterface.MESSAGE_RULE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S79") public class FreeResourcesOfAutoCloseableInterface extends IssuableSubscriptionVisitor { private final Deque withinTry = new LinkedList<>(); diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java index 41a54c1ca..1ac657aa3 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java @@ -15,7 +15,7 @@ name = "Developpement", description = IncrementCheck.MESSAGERULE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S67") public class IncrementCheck extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java index d5ee088b3..0090a7ac5 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java @@ -16,7 +16,7 @@ name = "Developpement", description = InitializeBufferWithAppropriateSize.RULE_MESSAGE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GRSP0032") public class InitializeBufferWithAppropriateSize extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java index 91c88106c..6c8758aa0 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java @@ -21,8 +21,8 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC69", name = "Developpement", description = NoFunctionCallWhenDeclaringForLoop.MESSAGERULE, priority = Priority.MINOR, tags = { - "bug"}) +@Rule(key = "EC69", name = "Developpement", description = NoFunctionCallWhenDeclaringForLoop.MESSAGERULE, priority = Priority.MINOR, + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S69") public class NoFunctionCallWhenDeclaringForLoop extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java index d94f57676..0ee8a79c7 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java @@ -21,7 +21,7 @@ name = "Developpement", description = OptimizeReadFileExceptions.MESSAGERULE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "error-handling", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GRSP0028") public class OptimizeReadFileExceptions extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java index 3069393db..22fcaa86e 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java @@ -34,8 +34,8 @@ import org.sonar.plugins.java.api.tree.VariableTree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC63", name = "Developpement", description = "Do not unnecessarily assign values to variables", priority = Priority.MINOR, tags = { - "bug"}) +@Rule(key = "EC63", name = "Developpement", description = "Do not unnecessarily assign values to variables", priority = Priority.MINOR, + tags = {"eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S63") public class UnnecessarilyAssignValuesToVariables extends BaseTreeVisitor implements JavaFileScanner { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java index 767f3449b..5cbc68e2f 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java @@ -16,7 +16,7 @@ name = "Developpement", description = UseCorrectForLoop.MESSAGERULE, priority = Priority.MINOR, - tags = {"bug"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S53") public class UseCorrectForLoop extends IssuableSubscriptionVisitor { From 3163c54a1eaca2320325f4ffb5a8d312bc30d413 Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Mon, 29 May 2023 11:24:02 +0200 Subject: [PATCH 063/170] refactor: update php rule html descriptions --- .../fr/greencodeinitiative/l10n/php/rules/custom/EC66.html | 4 ++-- .../fr/greencodeinitiative/l10n/php/rules/custom/EC69.html | 4 ++-- .../fr/greencodeinitiative/l10n/php/rules/custom/EC74.html | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC66.html b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC66.html index 5e06ebef7..233604feb 100644 --- a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC66.html +++ b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC66.html @@ -1,4 +1,4 @@ -

      PHP allows declaring a string with simple or double quotes. Using double quotes allows developers to insert variables which will be substituted during execution. When the string has no variables, using simple quotes avoid PHP to search inexisting variables. It will save CPU cycles consumption and RAM usage.

      +

      PHP allows declaring a string with simple or double quotes. Using double quotes allows developers to insert variables which will be substituted during execution. When the string has no variables, using single quotes prevents PHP from searching for non-existent variables. It will save CPU cycles consumption and RAM usage.

      Noncompliant Code Example

       myFunction("name", "age", "IsStudent");
      @@ -91,4 +91,4 @@ 

      Total:

      - \ No newline at end of file + diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC69.html b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC69.html index 655f6cab1..c71d96a37 100644 --- a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC69.html +++ b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC69.html @@ -1,4 +1,4 @@ -

      Do not call a function when declaring a for-type loop in order to avoid function calls each iterations. It saves CPU cycles.

      +

      Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.

      Noncompliant Code Example

       for ($i = 0; $i <= foo(); $i++) {  // Noncompliant
      @@ -101,4 +101,4 @@ 

      Total:

      - \ No newline at end of file + diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC74.html b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC74.html index 3b1edba30..d0a9c2f1a 100644 --- a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC74.html +++ b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC74.html @@ -1,4 +1,4 @@ -

      Databases servers have to solve fields regarding the schema. Knowing and using the schema save CPU cycles and network transfer.

      +

      Database servers have to resolve issues regarding schema fields. Knowing and using the schema save CPU cycles and network transfer.

      Noncompliant Code Example

           public function foo() {
      @@ -12,7 +12,7 @@ 

      Compliant Solution

           public function foo() {
               ...
      -        $baseQuery = "SELECT id,name, adress FROM users ";
      +        $baseQuery = "SELECT id,name, address FROM users ";
               ...
          }
       
      @@ -98,4 +98,4 @@

      Total:

      - \ No newline at end of file + From 16fa832089a8c7e13b05c5c370e66f126877e93b Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Mon, 29 May 2023 11:26:28 +0200 Subject: [PATCH 064/170] refactor: update tags for php rules --- .../greencodeinitiative/php/checks/AvoidDoubleQuoteCheck.java | 2 +- .../php/checks/AvoidFullSQLRequestCheck.java | 2 +- .../php/checks/AvoidSQLRequestInLoopCheck.java | 2 +- .../AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.java | 2 +- .../php/checks/AvoidUsingGlobalVariablesCheck.java | 2 +- .../java/fr/greencodeinitiative/php/checks/IncrementCheck.java | 2 +- .../php/checks/NoFunctionCallWhenDeclaringForLoop.java | 2 +- .../php/checks/UseOfMethodsForBasicOperations.java | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheck.java index 2fe45079c..cc89b1600 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheck.java @@ -19,7 +19,7 @@ name = AvoidDoubleQuoteCheck.ERROR_MESSAGE, description = AvoidDoubleQuoteCheck.ERROR_MESSAGE, priority = Priority.MINOR, - tags = {"bug", "eco-design", "ecocode"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S66") public class AvoidDoubleQuoteCheck extends PHPSubscriptionCheck { diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheck.java index fdc016916..c6fe2b28a 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheck.java @@ -17,7 +17,7 @@ name = AvoidFullSQLRequestCheck.ERROR_MESSAGE, description = AvoidFullSQLRequestCheck.ERROR_MESSAGE, priority = Priority.MINOR, - tags = {"bug", "eco-design", "ecocode"}) + tags = {"sql", "performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S74") public class AvoidFullSQLRequestCheck extends PHPSubscriptionCheck { diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheck.java index 358f43008..8a392fcb3 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheck.java @@ -23,7 +23,7 @@ name = AvoidSQLRequestInLoopCheck.ERROR_MESSAGE, description = AvoidSQLRequestInLoopCheck.ERROR_MESSAGE, priority = Priority.MINOR, - tags = {"bug", "eco-design", "ecocode"}) + tags = {"sql", "performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S72") public class AvoidSQLRequestInLoopCheck extends PHPSubscriptionCheck { diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.java index bced0aa40..fa818f8c5 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.java @@ -14,7 +14,7 @@ name = AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.ERROR_MESSAGE, description = AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.ERROR_MESSAGE, priority = Priority.MINOR, - tags = {"bug", "eco-design", "ecocode"}) + tags = {"error-handling", "performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S34") public class AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements extends PHPSubscriptionCheck { diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheck.java index 76607760d..7eecfdb2a 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheck.java @@ -13,7 +13,7 @@ name = AvoidUsingGlobalVariablesCheck.ERROR_MESSAGE, description = AvoidUsingGlobalVariablesCheck.ERROR_MESSAGE, priority = Priority.MINOR, - tags = {"bug", "eco-design", "ecocode"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "D4") public class AvoidUsingGlobalVariablesCheck extends PHPVisitorCheck { diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java index ba2c09e57..1c6168ca3 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java @@ -34,7 +34,7 @@ name = IncrementCheck.ERROR_MESSAGE, description = IncrementCheck.ERROR_MESSAGE, priority = Priority.MINOR, - tags = {"bug", "eco-design", "ecocode"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S67") public class IncrementCheck extends PHPSubscriptionCheck { diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoop.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoop.java index 4381c8a12..39ddca9a4 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoop.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoop.java @@ -19,7 +19,7 @@ name = NoFunctionCallWhenDeclaringForLoop.ERROR_MESSAGE, description = NoFunctionCallWhenDeclaringForLoop.ERROR_MESSAGE, priority = Priority.MINOR, - tags = {"bug", "eco-design", "ecocode"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S69") public class NoFunctionCallWhenDeclaringForLoop extends PHPSubscriptionCheck { diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperations.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperations.java index 4af8d8d9e..a1d03d769 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperations.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperations.java @@ -23,7 +23,7 @@ name = UseOfMethodsForBasicOperations.ERROR_MESSAGE, description = UseOfMethodsForBasicOperations.ERROR_MESSAGE, priority = Priority.MINOR, - tags = {"bug", "eco-design", "ecocode"}) + tags = {"performance", "eco-design", "ecocode"}) @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "D2") public class UseOfMethodsForBasicOperations extends PHPSubscriptionCheck { From d5506d8070f12a3a1be90054500937d3c7ac2587 Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Mon, 29 May 2023 12:29:06 +0200 Subject: [PATCH 065/170] refactor: rephrase rule EC74 html description for php, java, and python plugins --- .../fr/greencodeinitiative/l10n/java/rules/java/EC74.html | 4 ++-- .../fr/greencodeinitiative/l10n/php/rules/custom/EC74.html | 2 +- .../fr/greencodeinitiative/l10n/python/rules/python/EC74.html | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC74.html b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC74.html index d3f65bcf6..35ffbf7af 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC74.html +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC74.html @@ -1,4 +1,4 @@ -

      Databases servers have to solve fields regarding the schema. Knowing and using the schema save CPU cycles and network transfer.

      +

      Database servers have to resolve schema fields when using asterisk symbol (*). Knowing and using the schema saves CPU cycles and network transfer.

      Noncompliant Code Example

           public void foo() {
      @@ -14,7 +14,7 @@ 

      Compliant Solution

      public void foo() { ... - String query = "SELECT id,name, adress FROM users "; + String query = "SELECT id, name, address FROM users "; ... } diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC74.html b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC74.html index d0a9c2f1a..de53be78e 100644 --- a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC74.html +++ b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC74.html @@ -1,4 +1,4 @@ -

      Database servers have to resolve issues regarding schema fields. Knowing and using the schema save CPU cycles and network transfer.

      +

      Database servers have to resolve schema fields when using asterisk symbol (*). Knowing and using the schema saves CPU cycles and network transfer.

      Noncompliant Code Example

           public function foo() {
      diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC74.html b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC74.html
      index a18770333..35ffbf7af 100644
      --- a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC74.html
      +++ b/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC74.html
      @@ -1,4 +1,4 @@
      -

      Database servers have to resolve issues regarding schema fields. Knowing and using the schema save CPU cycles and network transfer.

      +

      Database servers have to resolve schema fields when using asterisk symbol (*). Knowing and using the schema saves CPU cycles and network transfer.

      Noncompliant Code Example

           public void foo() {
      @@ -14,7 +14,7 @@ 

      Compliant Solution

      public void foo() { ... - String query = "SELECT id,name, adress FROM users "; + String query = "SELECT id, name, address FROM users "; ... } From 29e40a7f55ebebfc96065bb547b6f36075e29297 Mon Sep 17 00:00:00 2001 From: utarwyn Date: Mon, 29 May 2023 19:52:11 +0200 Subject: [PATCH 066/170] Add JavaScript rules from eslint-plugin 0.2.0 --- .../l10n/javascript/rules.json | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/javascript-plugin/src/main/resources/fr/greencodeinitiative/l10n/javascript/rules.json b/javascript-plugin/src/main/resources/fr/greencodeinitiative/l10n/javascript/rules.json index e86627bb5..598525441 100644 --- a/javascript-plugin/src/main/resources/fr/greencodeinitiative/l10n/javascript/rules.json +++ b/javascript-plugin/src/main/resources/fr/greencodeinitiative/l10n/javascript/rules.json @@ -34,5 +34,29 @@ "eco-design", "ecocode" ] + }, + { + "key": "@ecocode/no-multiple-style-changes", + "type": "CODE_SMELL", + "name": "Disallow multiple style changes at once", + "description": "\n\n

      Rule Details

      \n

      This rule aims to disallow batching multiple style changes at once.

      \n

      To limit the number of repaint/reflow, it is advised to batch style modifications by adding a class containing all style\nchanges that will generate a unique reflow.

      \n

      Examples

      \n

      Examples of non-compliant code for this rule:

      \n
      <script>\n  element.style.height = "800px";\n  element.style.width = "600px";\n  element.style.color = "red";\n</script>\n
      \n

      Examples of compliant code for this rule:

      \n
      <style>\n  .in-error {\n    color: red;\n    height: 800px;\n    width: 800px;\n  }\n</style>\n\n<script>\n  element.addClass("in-error");\n</script>\n
      \n
      Click here to access the rule details.", + "constantDebtMinutes": 5, + "severity": "MINOR", + "tags": [ + "eco-design", + "ecocode" + ] + }, + { + "key": "@ecocode/prefer-collections-with-pagination", + "type": "CODE_SMELL", + "name": "Prefer API collections with pagination", + "description": "\n\n

      Rule details

      \n

      This rule aims to reduce the size and thus the network weight of API returns that may contain many elements. This rule\nis built for the NestJS framework but can work with a controller @Controller() and a decorated method @Get().

      \n

      Examples

      \n

      Examples of non-compliant code for this rule:

      \n
      @Controller()\nclass Test {\n  @Get()\n  public find(): Promise<string[]> {}\n}\n
      \n

      Examples of compliant code for this rule:

      \n
      interface Pagination {\n  items: string[];\n  currentPage: number;\n  totalPages: number;\n}\n\n@Controller()\nclass Test {\n  @Get()\n  public find(): Promise<Pagination> {}\n}\n
      \n
      Click here to access the rule details.", + "constantDebtMinutes": 5, + "severity": "MINOR", + "tags": [ + "eco-design", + "ecocode" + ] } ] From d4aa0fdf007d5bf07234eee54db1071a0c483678 Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Mon, 29 May 2023 23:12:43 +0200 Subject: [PATCH 067/170] refactor: update json rule descriptions for Java plugin --- .../greencodeinitiative/l10n/java/rules/java/EC1.json | 6 +++--- .../greencodeinitiative/l10n/java/rules/java/EC2.json | 3 +-- .../greencodeinitiative/l10n/java/rules/java/EC27.json | 5 ++--- .../greencodeinitiative/l10n/java/rules/java/EC28.json | 3 ++- .../greencodeinitiative/l10n/java/rules/java/EC3.json | 3 +-- .../greencodeinitiative/l10n/java/rules/java/EC32.json | 5 ++--- .../greencodeinitiative/l10n/java/rules/java/EC4.json | 5 ++--- .../greencodeinitiative/l10n/java/rules/java/EC5.json | 6 +++--- .../greencodeinitiative/l10n/java/rules/java/EC53.json | 3 +-- .../greencodeinitiative/l10n/java/rules/java/EC63.json | 7 +++---- .../greencodeinitiative/l10n/java/rules/java/EC67.json | 3 +-- .../greencodeinitiative/l10n/java/rules/java/EC69.json | 5 ++--- .../greencodeinitiative/l10n/java/rules/java/EC72.json | 10 +++++----- .../greencodeinitiative/l10n/java/rules/java/EC74.json | 3 +-- .../greencodeinitiative/l10n/java/rules/java/EC75.json | 7 +++---- .../greencodeinitiative/l10n/java/rules/java/EC76.json | 9 +++++---- .../greencodeinitiative/l10n/java/rules/java/EC77.json | 8 ++++---- .../greencodeinitiative/l10n/java/rules/java/EC78.json | 9 ++++----- .../greencodeinitiative/l10n/java/rules/java/EC79.json | 2 +- 19 files changed, 46 insertions(+), 56 deletions(-) diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC1.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC1.json index d8da6723c..5b583dcfe 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC1.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC1.json @@ -7,10 +7,10 @@ "constantCost": "50min" }, "tags": [ - "eco-design", "performance", - "bug", + "spring", + "eco-design", "ecocode" ], "defaultSeverity": "Minor" -} \ No newline at end of file +} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC2.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC2.json index c4f0f80ab..d48945c08 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC2.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC2.json @@ -9,8 +9,7 @@ "tags": [ "eco-design", "performance", - "bug", "ecocode" ], "defaultSeverity": "Minor" -} \ No newline at end of file +} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC27.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC27.json index 13530377d..eaa045e90 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC27.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC27.json @@ -7,10 +7,9 @@ "constantCost": "20min" }, "tags": [ - "eco-design", "performance", - "bug", + "eco-design", "ecocode" ], "defaultSeverity": "Minor" -} \ No newline at end of file +} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC28.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC28.json index 80cf37817..c85d2ee51 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC28.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC28.json @@ -7,8 +7,9 @@ "constantCost": "5min" }, "tags": [ + "performance", + "error-handling", "eco-design", - "bug", "ecocode" ], "defaultSeverity": "Minor" diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC3.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC3.json index a8b365948..f511c1c2a 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC3.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC3.json @@ -9,8 +9,7 @@ "tags": [ "eco-design", "performance", - "bug", "ecocode" ], "defaultSeverity": "Minor" -} \ No newline at end of file +} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC32.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC32.json index 9a76c4c9e..95e1d7b33 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC32.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC32.json @@ -7,10 +7,9 @@ "constantCost": "5min" }, "tags": [ - "eco-design", "performance", - "bug", + "eco-design", "ecocode" ], "defaultSeverity": "Minor" -} \ No newline at end of file +} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC4.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC4.json index 292eca846..0cf5108bd 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC4.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC4.json @@ -7,10 +7,9 @@ "constantCost": "5min" }, "tags": [ - "eco-design", "performance", - "bug", + "eco-design", "ecocode" ], "defaultSeverity": "Minor" -} \ No newline at end of file +} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC5.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC5.json index 1095573a9..6629e0943 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC5.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC5.json @@ -7,10 +7,10 @@ "constantCost": "10min" }, "tags": [ - "eco-design", "performance", - "bug", + "sql", + "eco-design", "ecocode" ], "defaultSeverity": "Minor" -} \ No newline at end of file +} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC53.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC53.json index f6411338f..3b1f7e72b 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC53.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC53.json @@ -7,9 +7,8 @@ "constantCost": "5min" }, "tags": [ - "eco-design", "performance", - "bug", + "eco-design", "ecocode" ], "defaultSeverity": "Minor" diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC63.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC63.json index b09e15020..dc9189905 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC63.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC63.json @@ -8,9 +8,8 @@ }, "tags": [ "eco-design", - "memory", - "bug", - "ecocode" + "ecocode", + "memory" ], "defaultSeverity": "Minor" -} \ No newline at end of file +} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC67.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC67.json index a13d7e7cd..824d66d16 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC67.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC67.json @@ -7,9 +7,8 @@ "constantCost": "5min" }, "tags": [ - "eco-design", "performance", - "bug", + "eco-design", "ecocode" ], "defaultSeverity": "Minor" diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC69.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC69.json index f00a9b99b..b66f24ee0 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC69.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC69.json @@ -7,10 +7,9 @@ "constantCost": "5min" }, "tags": [ - "eco-design", "performance", - "bug", + "eco-design", "ecocode" ], "defaultSeverity": "Minor" -} \ No newline at end of file +} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC72.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC72.json index 3cbb604ed..5fdf8c909 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC72.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC72.json @@ -7,13 +7,13 @@ "constantCost": "10min" }, "tags": [ - "eco-design", "performance", - "memory", - "network", "sql", - "bug", - "ecocode" + "spring", + "eco-design", + "ecocode", + "memory", + "network" ], "defaultSeverity": "Minor" } diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC74.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC74.json index 64ba5a125..7a4eea182 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC74.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC74.json @@ -11,8 +11,7 @@ "performance", "network", "sql", - "bug", "ecocode" ], "defaultSeverity": "Minor" -} \ No newline at end of file +} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC75.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC75.json index 1f4c21348..42cef3012 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC75.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC75.json @@ -7,11 +7,10 @@ "constantCost": "20min" }, "tags": [ - "eco-design", "performance", - "memory", - "bug", - "ecocode" + "eco-design", + "ecocode", + "memory" ], "defaultSeverity": "Minor" } diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC76.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC76.json index 246fb1b85..95b8bc483 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC76.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC76.json @@ -7,10 +7,11 @@ "constantCost": "20min" }, "tags": [ + "cwe", + "leak", "eco-design", - "memory", - "bug", - "ecocode" + "ecocode", + "memory" ], "defaultSeverity": "Minor" -} \ No newline at end of file +} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC77.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC77.json index fa21f3110..2aa53debd 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC77.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC77.json @@ -7,11 +7,11 @@ "constantCost": "20min" }, "tags": [ - "eco-design", "performance", - "memory", - "bug", - "ecocode" + "regex", + "eco-design", + "ecocode", + "memory" ], "defaultSeverity": "Minor" } diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC78.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC78.json index eb97c43c2..6525cb823 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC78.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC78.json @@ -8,11 +8,10 @@ }, "tags": [ "eco-design", - "performance", - "memory", + "ecocode", "sql", - "bug", - "ecocode" + "performance", + "memory" ], "defaultSeverity": "Minor" -} \ No newline at end of file +} diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC79.json b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC79.json index 9d74b48fe..968adfe0c 100644 --- a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC79.json +++ b/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC79.json @@ -7,8 +7,8 @@ "constantCost": "15min" }, "tags": [ + "performance", "eco-design", - "bug", "ecocode" ], "defaultSeverity": "Minor" From 080bfceeb3865b99acdf735f3098876b31196ba7 Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Mon, 29 May 2023 23:13:04 +0200 Subject: [PATCH 068/170] refactor: update Java rule tags --- .../java/checks/AvoidConcatenateStringsInLoop.java | 2 +- .../fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java | 2 +- .../java/checks/AvoidRegexPatternNotStatic.java | 2 +- .../greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java | 2 +- .../java/checks/AvoidSetConstantInBatchUpdate.java | 2 +- .../java/checks/AvoidUsageOfStaticCollections.java | 2 +- .../java/checks/UnnecessarilyAssignValuesToVariables.java | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java index 9b203f3fa..996043b5a 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java @@ -20,7 +20,7 @@ name = "Developpement", description = AvoidConcatenateStringsInLoop.MESSAGE_RULE, priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) + tags = {"performance", "eco-design", "ecocode", "memory"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S75") public class AvoidConcatenateStringsInLoop extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java index 2913e970e..3d9bcc22f 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java @@ -19,7 +19,7 @@ name = "Developpement", description = AvoidFullSQLRequest.MESSAGERULE, priority = Priority.MINOR, - tags = {"performance", "sql", "eco-design", "ecocode"}) + tags = {"performance", "sql", "eco-design", "ecocode", "network"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S74") public class AvoidFullSQLRequest extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java index 6968e4e4e..4b6949cce 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java @@ -21,7 +21,7 @@ name = "Developpement", description = AvoidRegexPatternNotStatic.MESSAGE_RULE, priority = Priority.MINOR, - tags = {"performance", "regex", "eco-design", "ecocode"}) + tags = {"performance", "regex", "eco-design", "ecocode", "memory"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S77") public class AvoidRegexPatternNotStatic extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java index 4acbaaf55..532b89c12 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java @@ -15,7 +15,7 @@ import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; @Rule(key = "EC72", name = "Developpement", description = AvoidSQLRequestInLoop.MESSAGERULE, priority = Priority.MINOR, - tags = {"performance", "sql", "spring", "eco-design", "ecocode"}) + tags = {"performance", "sql", "spring", "eco-design", "ecocode", "memory", "network"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S72") public class AvoidSQLRequestInLoop extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java index 0a59633f8..9a692f82d 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java @@ -24,7 +24,7 @@ @Rule(key = "EC78", name = "Developpement", description = AvoidSetConstantInBatchUpdate.MESSAGERULE, priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) + tags = {"eco-design", "ecocode", "sql", "performance", "memory"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S78") public class AvoidSetConstantInBatchUpdate extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java index c75490de7..d4de0d49e 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java @@ -19,7 +19,7 @@ name = "Developpement", description = AvoidUsageOfStaticCollections.MESSAGE_RULE, priority = Priority.MINOR, - tags = {"cwe", "leak", "eco-design", "ecocode"}) + tags = {"cwe", "leak", "eco-design", "ecocode", "memory"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S76") public class AvoidUsageOfStaticCollections extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java index 22fcaa86e..0e334905d 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java @@ -35,7 +35,7 @@ import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; @Rule(key = "EC63", name = "Developpement", description = "Do not unnecessarily assign values to variables", priority = Priority.MINOR, - tags = {"eco-design", "ecocode"}) + tags = {"eco-design", "ecocode", "memory"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S63") public class UnnecessarilyAssignValuesToVariables extends BaseTreeVisitor implements JavaFileScanner { From 335d7d0ffe65abc14d4d4ab90a03cc9d60259ae0 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Wed, 31 May 2023 11:24:25 +0200 Subject: [PATCH 069/170] updating rule and tests --- CHANGELOG.md | 3 +- RULES.md | 2 +- ...idGettingSizeCollectionInForLoopCheck.java | 24 +-- .../AvoidGettingSizeCollectionInForLoop.php | 156 +++++++++++++----- 4 files changed, 128 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c42bb9f8..74eb9303a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- [#109](https://github.com/green-code-initiative/ecoCode/issues/109) PHP rule : **Getting the size of the collection in the loop**. For further [RULES.md](./RULES.md) file. ### Changed @@ -64,7 +65,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#33](https://github.com/green-code-initiative/ecoCode/issues/33) Update plugin description in code - [#42](https://github.com/green-code-initiative/ecoCode/issues/42) Fix Crash SonarQube analysis because of some ClassCast Exceptions - [#48](https://github.com/green-code-initiative/ecoCode/pull/48) correction SONAR issue info - delete public keyword on tests -- Improve "build" Github actions to execute checks on branches from fork repositories +- Improve "build" GitHub actions to execute checks on branches from fork repositories ## [0.2.1] - 2022-12-30 diff --git a/RULES.md b/RULES.md index d40de3775..96fd6a8e2 100644 --- a/RULES.md +++ b/RULES.md @@ -36,7 +36,7 @@ Some are applicable for different technologies. | EC72 | Perform an SQL query inside a loop | Servers are optimized to process multiple selections, insertions, or changes in a single query or transaction. consume CPU cycles, RAM, and bandwidth unnecessarily. | [cnumr best practices (3rd edition) BP_072](https://github.com/cnumr/best-practices/blob/main/chapters/BP_072_fr.md) | ✅ | ✅ | 🚀 | ✅ | 🚀 | | EC74 | Write SELECT * FROM | The database server must resolve the fields based on the schema. If you are familiar with the diagram, it is strongly recommended to name the fields. | [cnumr best practices (3rd edition) BP_074 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | ✅ | 🚀 | | EC1 | Calling a Spring repository inside a loop | The use of Spring repository in a loop induces unnecessary calculations by the CPU and therefore superfluous energy consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | -| EC3 | Getting the size of the collection in the loop | When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. | | ✅ | 🚀 | 🚀 | 🚀 | 🚀 | +| EC3 | Getting the size of the collection in the loop | When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. | | ✅ | ✅ | 🚀 | 🚀 | 🚀 | | EC2 | Multiple if-else statement | Using too many conditional if-else statements will impact performance since JVM will have to compare the conditions. Prefer using a switch statement instead of multiple if-else if possible. Switch statement has a performance advantage over if – else. | | ✅ | 🚀 | 🚀 | 🚀 | 🚀 | | EC76 | Usage of static collections | Avoid usage of static collections. If you want to use static collections make them final and create for example a singleton if needed containing the collections. The static fields are more complicated for the Garbage Collector to manage and can lead to memory leaks. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | | EC77 | Usage Pattern.compile() in a non-static context | Avoid using Pattern.compile() in a non-static context. This operation requires a non negligible amount of computational power, Using a single match saves CPU cycles and RAM consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java index fa5bc8cd0..ce98aeca3 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java @@ -4,7 +4,6 @@ import org.sonar.check.Rule; import org.sonar.plugins.php.api.tree.SeparatedList; import org.sonar.plugins.php.api.tree.Tree; -import org.sonar.plugins.php.api.tree.expression.BinaryExpressionTree; import org.sonar.plugins.php.api.tree.expression.ExpressionTree; import org.sonar.plugins.php.api.tree.expression.ParenthesisedExpressionTree; import org.sonar.plugins.php.api.tree.statement.*; @@ -19,45 +18,48 @@ name = AvoidGettingSizeCollectionInForLoopCheck.ERROR_MESSAGE, description = AvoidGettingSizeCollectionInForLoopCheck.ERROR_MESSAGE, priority = Priority.MINOR, - tags = {"bug", "eco-design", "ecocode"}) + tags = {"eco-design", "ecocode"}) public class AvoidGettingSizeCollectionInForLoopCheck extends PHPSubscriptionCheck { public static final String RULE_KEY = "EC3"; public static final String ERROR_MESSAGE = "Avoid getting the size of the collection in the loop"; - private static final Pattern PATTERN = Pattern.compile("\\b(?:count|sizeof)\\b"); + private static final Pattern PATTERN = Pattern.compile("\\b(?:count|sizeof|iterator_count)\\b"); @Override public List nodesToVisit() { - return Arrays.asList(Tree.Kind.FOR_STATEMENT, Tree.Kind.WHILE_STATEMENT, Tree.Kind.DO_WHILE_STATEMENT); + return Arrays.asList( + Tree.Kind.FOR_STATEMENT, + Tree.Kind.ALTERNATIVE_FOR_STATEMENT, + Tree.Kind.WHILE_STATEMENT, + Tree.Kind.DO_WHILE_STATEMENT + ); } @Override public void visitNode(Tree tree) { - if (tree.is(Tree.Kind.FOR_STATEMENT)) { + if (tree.is(Tree.Kind.FOR_STATEMENT) || tree.is(Tree.Kind.ALTERNATIVE_FOR_STATEMENT)) { ForStatementTree conditionTree = (ForStatementTree) tree; SeparatedList conditions = conditionTree.condition(); for (ExpressionTree condition : conditions) { - if (condition instanceof BinaryExpressionTree) { - verifyIfThereIsAError(((BinaryExpressionTree) condition).rightOperand().toString(), conditionTree); - } + verifyAndLaunchError(condition.toString(), conditionTree); } } if (tree.is(Tree.Kind.WHILE_STATEMENT)) { WhileStatementTree whileTree = (WhileStatementTree) tree; ParenthesisedExpressionTree condition = whileTree.condition(); - verifyIfThereIsAError(condition.expression().toString(), whileTree); + verifyAndLaunchError(condition.expression().toString(), whileTree); } if (tree.is(Tree.Kind.DO_WHILE_STATEMENT)) { DoWhileStatementTree doWhileTree = (DoWhileStatementTree) tree; ParenthesisedExpressionTree condition = doWhileTree.condition(); - verifyIfThereIsAError(condition.expression().toString(), doWhileTree); + verifyAndLaunchError(condition.expression().toString(), doWhileTree); } } - private void verifyIfThereIsAError(String condition, StatementTree conditionTree) { + private void verifyAndLaunchError(String condition, StatementTree conditionTree) { if (PATTERN.matcher(condition).find()) { context().newIssue(this, conditionTree, ERROR_MESSAGE); } diff --git a/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php b/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php index 4fa8d242b..568759dde 100644 --- a/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php +++ b/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php @@ -1,52 +1,107 @@ $i; ++$i) { // NOK {{Avoid getting the size of the collection in the loop}} + var_dump($array[$i]); +} + +$size = count($array); +for ($i = 0; $size > $i; ++$i) { // Compliant + var_dump($array[$i]); +} + +for ($i = 0; sizeof($array) > $i; ++$i) { // NOK {{Avoid getting the size of the collection in the loop}} + var_dump($array[$i]); +} + +$size = sizeof($array); +for ($i = 0; $size > $i; ++$i) { // Compliant + var_dump($array[$i]); +} + +for ($i = 0; iterator_count(new ArrayIterator($array)) > $i; ++$i) { // NOK {{Avoid getting the size of the collection in the loop}} + var_dump($array[$i]); +} + +$size = iterator_count(new ArrayIterator($array)); +for ($i = 0; $size > $i; ++$i) { // Compliant + var_dump($array[$i]); +} /** * WHILE STATEMENTS */ $i = 0; -while($i < count($food)) // NOK {{Avoid getting the size of the collection in the loop}} -{ - var_dump($food[$i]); - $i++; +while ($i < count($array)) { // NOK {{Avoid getting the size of the collection in the loop}} + var_dump($array[$i]); + ++$i; +} + +$i = 0; +$size = count($array); +while ($i < $size) { // Compliant + var_dump($array[$i]); + ++$i; +} + +$i = 0; +while ($i < sizeof($array)) { // NOK {{Avoid getting the size of the collection in the loop}} + var_dump($array[$i]); + ++$i; } $i = 0; -$size = count($food); -while($i < $size) -{ - var_dump($food[$i]); - $i++; +$size = sizeof($array); +while ($i < $size) { // Compliant + var_dump($array[$i]); + ++$i; } $i = 0; -$size = sizeof($food); -while($i < $size) -{ - var_dump($food[$i]); - $i++; +while ($i < iterator_count(new ArrayIterator($array))) { // NOK {{Avoid getting the size of the collection in the loop}} + var_dump($array[$i]); + ++$i; +} + +$i = 0; +$size = iterator_count(new ArrayIterator($array)); +while ($i < $size) { // Compliant + var_dump($array[$i]); + ++$i; } /** @@ -54,26 +109,39 @@ */ $i = 0; do { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($food[$i]); - $i++; -} while ($i < count($food)); + var_dump($array[$i]); + ++$i; +} while ($i < count($array)); + +$i = 0; +$size = count($array); +do { + var_dump($array[$i]); + ++$i; +} while ($i < $size); // Compliant + +$i = 0; +do { // NOK {{Avoid getting the size of the collection in the loop}} + var_dump($array[$i]); + ++$i; +} while ($i < sizeof($array)); $i = 0; -$size = count($food); +$size = sizeof($array); do { - var_dump($food[$i]); - $i++; -} while ($i < $size); + var_dump($array[$i]); + ++$i; +} while ($i < $size); // Compliant $i = 0; do { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($food[$i]); - $i++; -} while ($i < sizeof($food)); + var_dump($array[$i]); + ++$i; +} while ($i < iterator_count(new ArrayIterator($array))); $i = 0; -$size = sizeof($food); +$size = iterator_count(new ArrayIterator($array)); do { - var_dump($food[$i]); - $i++; -} while ($i < $size); \ No newline at end of file + var_dump($array[$i]); + ++$i; +} while ($i < $size); // Compliant From 462ec438b45d0884835929a3e6fb025f7c6b75a8 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Wed, 31 May 2023 14:24:34 +0200 Subject: [PATCH 070/170] removing useless imports + cleanning the doc --- .../php/PhpRuleRepository.java | 2 +- .../l10n/php/rules/custom/EC3.html | 60 +++++++++++-------- 2 files changed, 36 insertions(+), 26 deletions(-) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java index 220f6259c..48a03943e 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java @@ -28,7 +28,7 @@ import java.util.List; import java.util.Map; -import fr.greencodeinitiative.php.checks.*; +import fr.greencodeinitiative.php.checks.AvoidGettingSizeCollectionInForLoopCheck; import fr.greencodeinitiative.php.checks.AvoidDoubleQuoteCheck; import fr.greencodeinitiative.php.checks.AvoidFullSQLRequestCheck; import fr.greencodeinitiative.php.checks.AvoidSQLRequestInLoopCheck; diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html index f7ac23654..3ae59b9e9 100644 --- a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html +++ b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html @@ -1,55 +1,65 @@

      When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power.

      +

      NB : note that we are using the count() method to get the size of an array but it would work the same with the sizeof() and iterator_count() methods

      -

      Noncompliant Code Example

      +

      Noncompliant Code Examples

      -	$food = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
      +	$array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
       
      -	// FOR STATEMENTS
      -	for ($i = 0; $i < count($food); $i++) {
      -		var_dump($food[$i]);
      +	// FOR STATEMENTS / Right operand
      +	for ($i = 0; $i < count($array); ++$i) {
      +		var_dump($array[$i]);
      +	}
      +
      +	// FOR STATEMENTS / Left operand
      +	for ($i = 0; count($array) > $i; ++$i) {
      +		var_dump($array[$i]);
       	}
       
       	// WHILE STATEMENTS
       	$i = 0;
      -	while($i < count($food))
      -	{
      -		var_dump($food[$i]);
      -		$i++;
      +	while($i < count($array)) {
      +		var_dump($array[$i]);
      +		++$i;
       	}
       
       	// DO WHILE STATEMENTS
       	$i = 0;
       	do {
      -		var_dump($food[$i]);
      -		$i++;
      -	} while ($i < count($food));
      +		var_dump($array[$i]);
      +		++$i;
      +	} while ($i < count($array));
       
       

      Compliant Solution

      -	$food = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
      -	// FOR STATEMENTS
      -	$size = sizeof($food);
      -	for ($i = 0; $i < $size; $i++) {
      -		var_dump($food[$i]);
      +	$array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
      +	// FOR STATEMENTS / Right operand
      +	$size = sizeof($array);
      +	for ($i = 0; $i < $size; ++$i) {
      +		var_dump($array[$i]);
      +	}
      +
      +	// FOR STATEMENTS / Left operand
      +	$size = sizeof($array);
      +	for ($i = 0; $size > $i; ++$i) {
      +		var_dump($array[$i]);
       	}
       
       	// WHILE STATEMENTS
       	$i = 0;
      -	$size = count($food);
      -	while($i < $size)
      -	{
      -		var_dump($food[$i]);
      -		$i++;
      +	$size = count($array);
      +	while($i < $size) {
      +		var_dump($array[$i]);
      +		++$i;
       	}
       
       	// DO WHILE STATEMENTS
       	$i = 0;
      -	$size = count($food);
      +	$size = count($array);
       	do {
      -		var_dump($food[$i]);
      -		$i++;
      +		var_dump($array[$i]);
      +		++$i;
       	} while ($i < $size);
       
       
      From e9c8dea6425f056b4a136cf941cc2aaefa33fa0c Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Wed, 31 May 2023 14:32:23 +0200 Subject: [PATCH 071/170] resolve conflict --- .../greencodeinitiative/python/PythonRuleRepositoryTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java index 0c734cbfa..c21cc4fc8 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java @@ -44,8 +44,8 @@ public void init() { public void test() { assertThat(pythonRuleRepository.repositoryKey()).isEqualTo(PythonRuleRepository.REPOSITORY_KEY); assertThat(context.repositories()).hasSize(1).extracting("key").containsExactly(pythonRuleRepository.repositoryKey()); - assertThat(context.repositories().get(0).rules()).hasSize(9); - assertThat(pythonRuleRepository.checkClasses()).hasSize(9); + assertThat(context.repositories().get(0).rules()).hasSize(10); + assertThat(pythonRuleRepository.checkClasses()).hasSize(10); } From af3f95349b7fe6e24ddfc9f66d7a70e0323ee7b0 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Wed, 31 May 2023 15:16:01 +0200 Subject: [PATCH 072/170] updating RULES.md & CHANGELOG.md --- CHANGELOG.md | 1 + RULES.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb03809f2..8fa4f2f70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#113](https://github.com/green-code-initiative/ecoCode/issues/113) new PYTHON rule : Use unoptimized vector images - [#127](https://github.com/green-code-initiative/ecoCode/issues/127) Add Python rule EC404: Usage of generator comprehension instead of list comprehension in for loop declaration - [#192](https://github.com/green-code-initiative/ecoCode/pull/192) Add Python rule EC203: Detect unoptimized file formats +- [#108](https://github.com/green-code-initiative/ecoCode/issues/108) Add Python rule EC66: Use single quote (') instead of quotation mark (") ### Changed diff --git a/RULES.md b/RULES.md index 1837f959c..c248ee86e 100644 --- a/RULES.md +++ b/RULES.md @@ -30,7 +30,7 @@ Some are applicable for different technologies. | EC53 | Using arrays in foreach loops | foreach deduplicates items in a list before starting the enumeration. It is therefore generally more economical to use a simple for loop when you have a good command of the collection. | [cnumr best practices (3rd edition) BP_053 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | 🚀 | 🚀 | 🚀 | 🚀 | | EC7 | Rewrite native getter/setters | Overloading them lengthens the compilation and execution times of these methods, which are usually much better optimized by the language than by the developer. | [cnumr best practices (3rd edition) BP_062 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | 🚀 | 🚀 | ✅ | 🚀 | | EC63 | Unnecessarily assigning values to variables | Avoid declaring and using variables when it is not indis-thinkable. Indeed, each allocation corresponds to the RAM occupied. | [cnumr best practices (3rd edition) BP_063 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | 🚀 | 🚀 | 🚀 | 🚀 | -| EC66 | Use single quote (') instead of quotation mark (") | The shape using the quotation marks allows the developer to insert variables that will be substituted at run time. But if the string does not have a variable, use quotes instead. Thus, language will not look for variables to subtituture, which will reduce the consumption of CPU cycles. | [cnumr best practices (3rd edition) BP_066 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | ✅ | 🚀 | 🚀 | 🚀 | +| EC66 | Use single quote (') instead of quotation mark (") | The shape using the quotation marks allows the developer to insert variables that will be substituted at run time. But if the string does not have a variable, use quotes instead. Thus, language will not look for variables to subtituture, which will reduce the consumption of CPU cycles. | [cnumr best practices (3rd edition) BP_066 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | ✅ | 🚀 | ✅ | 🚀 | | EC67 | Use the $i++ variable during an iteration | The $i++ form has the disadvantage of generating a tem-porary variable during incrementation, which is not the case with the ++$i form. | [cnumr best practices (3rd edition) BP_067 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | 🚀 | 🚀 | | EC69 | Calling a function in the declaration of a for loop | Avoid calling the function each time the loop is iterated. | [cnumr best practices (3rd edition) BP_069 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | ✅ | 🚀 | | EC72 | Perform an SQL query inside a loop | Servers are optimized to process multiple selections, insertions, or changes in a single query or transaction. consume CPU cycles, RAM, and bandwidth unnecessarily. | [cnumr best practices (3rd edition) BP_072](https://github.com/cnumr/best-practices/blob/main/chapters/BP_072_fr.md) | ✅ | ✅ | 🚀 | ✅ | 🚀 | From 2bc96e887b4330a24e288ea417a54b84bf681668 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Wed, 31 May 2023 16:30:04 +0200 Subject: [PATCH 073/170] improvements after PR review --- ...idGettingSizeCollectionInForLoopCheck.java | 8 +- .../l10n/php/rules/custom/EC3.html | 36 +++++++- .../AvoidGettingSizeCollectionInForLoop.php | 88 ++++++++++++++++++- 3 files changed, 124 insertions(+), 8 deletions(-) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java index ce98aeca3..93c1f7f63 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java @@ -6,7 +6,10 @@ import org.sonar.plugins.php.api.tree.Tree; import org.sonar.plugins.php.api.tree.expression.ExpressionTree; import org.sonar.plugins.php.api.tree.expression.ParenthesisedExpressionTree; -import org.sonar.plugins.php.api.tree.statement.*; +import org.sonar.plugins.php.api.tree.statement.DoWhileStatementTree; +import org.sonar.plugins.php.api.tree.statement.ForStatementTree; +import org.sonar.plugins.php.api.tree.statement.StatementTree; +import org.sonar.plugins.php.api.tree.statement.WhileStatementTree; import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; import java.util.Arrays; @@ -18,7 +21,8 @@ name = AvoidGettingSizeCollectionInForLoopCheck.ERROR_MESSAGE, description = AvoidGettingSizeCollectionInForLoopCheck.ERROR_MESSAGE, priority = Priority.MINOR, - tags = {"eco-design", "ecocode"}) + tags = {"eco-design", "ecocode", "bad-practice", "performance"} +) public class AvoidGettingSizeCollectionInForLoopCheck extends PHPSubscriptionCheck { public static final String RULE_KEY = "EC3"; diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html index 3ae59b9e9..3eace53ff 100644 --- a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html +++ b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html @@ -15,20 +15,33 @@

      Noncompliant Code Examples

      var_dump($array[$i]); } - // WHILE STATEMENTS + // WHILE STATEMENTS / Right operand $i = 0; while($i < count($array)) { var_dump($array[$i]); ++$i; } - // DO WHILE STATEMENTS + // WHILE STATEMENTS / Left operand + $i = 0; + while(count($array) > $i) { + var_dump($array[$i]); + ++$i; + } + + // DO WHILE STATEMENTS / Right operand $i = 0; do { var_dump($array[$i]); ++$i; } while ($i < count($array)); + // DO WHILE STATEMENTS / Left operand + $i = 0; + do { + var_dump($array[$i]); + ++$i; + } while (count($array) > $i);

      Compliant Solution

      @@ -46,7 +59,7 @@

      Compliant Solution

      var_dump($array[$i]); } - // WHILE STATEMENTS + // WHILE STATEMENTS / Right operand $i = 0; $size = count($array); while($i < $size) { @@ -54,7 +67,15 @@

      Compliant Solution

      ++$i; } - // DO WHILE STATEMENTS + // WHILE STATEMENTS / Left operand + $i = 0; + $size = count($array); + while($size > $i) { + var_dump($array[$i]); + ++$i; + } + + // DO WHILE STATEMENTS / Right operand $i = 0; $size = count($array); do { @@ -62,4 +83,11 @@

      Compliant Solution

      ++$i; } while ($i < $size); + // DO WHILE STATEMENTS / Left operand + $i = 0; + $size = count($array); + do { + var_dump($array[$i]); + ++$i; + } while ($size > $i);
      diff --git a/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php b/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php index 568759dde..543a8b4a4 100644 --- a/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php +++ b/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php @@ -63,7 +63,7 @@ } /** - * WHILE STATEMENTS + * WHILE STATEMENTS // RIGHT OPERAND */ $i = 0; while ($i < count($array)) { // NOK {{Avoid getting the size of the collection in the loop}} @@ -105,7 +105,49 @@ } /** - * DO WHILE STATEMENTS + * WHILE STATEMENTS // LEFT OPERAND + */ +$i = 0; +while (count($array) > $i) { // NOK {{Avoid getting the size of the collection in the loop}} + var_dump($array[$i]); + ++$i; +} + +$i = 0; +$size = count($array); +while ($size> $i) { // Compliant + var_dump($array[$i]); + ++$i; +} + +$i = 0; +while (sizeof($array) > $i) { // NOK {{Avoid getting the size of the collection in the loop}} + var_dump($array[$i]); + ++$i; +} + +$i = 0; +$size = sizeof($array); +while ($size > $i) { // Compliant + var_dump($array[$i]); + ++$i; +} + +$i = 0; +while (iterator_count(new ArrayIterator($array)) > $i) { // NOK {{Avoid getting the size of the collection in the loop}} + var_dump($array[$i]); + ++$i; +} + +$i = 0; +$size = iterator_count(new ArrayIterator($array)); +while ($size > $i) { // Compliant + var_dump($array[$i]); + ++$i; +} + +/** + * DO WHILE STATEMENTS // RIGHT OPERAND */ $i = 0; do { // NOK {{Avoid getting the size of the collection in the loop}} @@ -145,3 +187,45 @@ var_dump($array[$i]); ++$i; } while ($i < $size); // Compliant + +/** + * DO WHILE STATEMENTS // LEFT OPERAND + */ +$i = 0; +do { // NOK {{Avoid getting the size of the collection in the loop}} + var_dump($array[$i]); + ++$i; +} while (count($array) > $i); + +$i = 0; +$size = count($array); +do { + var_dump($array[$i]); + ++$i; +} while ($size > $i); // Compliant + +$i = 0; +do { // NOK {{Avoid getting the size of the collection in the loop}} + var_dump($array[$i]); + ++$i; +} while (sizeof($array) > $i); + +$i = 0; +$size = sizeof($array); +do { + var_dump($array[$i]); + ++$i; +} while ($size > $i); // Compliant + +$i = 0; +do { // NOK {{Avoid getting the size of the collection in the loop}} + var_dump($array[$i]); + ++$i; +} while (iterator_count(new ArrayIterator($array)) > $i); + +$i = 0; +$size = iterator_count(new ArrayIterator($array)); +do { + var_dump($array[$i]); + ++$i; +} while ($size > $i); // Compliant From c2e68e5547c654761244be5b906ba5f77bf1a95e Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Wed, 31 May 2023 17:21:55 +0200 Subject: [PATCH 074/170] updating tags --- .../python/checks/AvoidDoubleQuoteCheck.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java index db3146318..033c468d1 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java @@ -12,7 +12,7 @@ name = AvoidDoubleQuoteCheck.MESSAGE_RULE, description = AvoidDoubleQuoteCheck.MESSAGE_RULE, priority = Priority.MINOR, - tags = {"bug", "eco-design", "ecocode"}) + tags = {"eco-design", "ecocode", "bad-practice"}) public class AvoidDoubleQuoteCheck extends PythonSubscriptionCheck { public static final String RULE_KEY = "EC66"; public static final String MESSAGE_RULE = "Avoid using quotation mark (\"), prefer using simple quote (')"; From b988967a83bcbaebac55ceb28dea45b047036dcc Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Thu, 1 Jun 2023 08:53:56 +0200 Subject: [PATCH 075/170] renamming classes --- .../fr/greencodeinitiative/php/PhpRuleRepository.java | 4 ++-- ...ck.java => AvoidGettingSizeCollectionInLoopCheck.java} | 8 ++++---- ...est.java => AvoidGettingSizeCollectionInLoopTest.java} | 4 ++-- ...InForLoop.php => AvoidGettingSizeCollectionInLoop.php} | 0 4 files changed, 8 insertions(+), 8 deletions(-) rename php-plugin/src/main/java/fr/greencodeinitiative/php/checks/{AvoidGettingSizeCollectionInForLoopCheck.java => AvoidGettingSizeCollectionInLoopCheck.java} (90%) rename php-plugin/src/test/java/fr/greencodeinitiative/php/checks/{AvoidGettingSizeCollectionInForLoopTest.java => AvoidGettingSizeCollectionInLoopTest.java} (53%) rename php-plugin/src/test/resources/checks/{AvoidGettingSizeCollectionInForLoop.php => AvoidGettingSizeCollectionInLoop.php} (100%) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java index 48a03943e..89d05f894 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java @@ -28,7 +28,7 @@ import java.util.List; import java.util.Map; -import fr.greencodeinitiative.php.checks.AvoidGettingSizeCollectionInForLoopCheck; +import fr.greencodeinitiative.php.checks.AvoidGettingSizeCollectionInLoopCheck; import fr.greencodeinitiative.php.checks.AvoidDoubleQuoteCheck; import fr.greencodeinitiative.php.checks.AvoidFullSQLRequestCheck; import fr.greencodeinitiative.php.checks.AvoidSQLRequestInLoopCheck; @@ -90,7 +90,7 @@ public String repositoryKey() { @Override public List> checkClasses() { return List.of( - AvoidGettingSizeCollectionInForLoopCheck.class, + AvoidGettingSizeCollectionInLoopCheck.class, AvoidDoubleQuoteCheck.class, AvoidFullSQLRequestCheck.class, AvoidSQLRequestInLoopCheck.class, diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopCheck.java similarity index 90% rename from php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java rename to php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopCheck.java index 93c1f7f63..7ef27ade9 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopCheck.java @@ -17,13 +17,13 @@ import java.util.regex.Pattern; @Rule( - key = AvoidGettingSizeCollectionInForLoopCheck.RULE_KEY, - name = AvoidGettingSizeCollectionInForLoopCheck.ERROR_MESSAGE, - description = AvoidGettingSizeCollectionInForLoopCheck.ERROR_MESSAGE, + key = AvoidGettingSizeCollectionInLoopCheck.RULE_KEY, + name = AvoidGettingSizeCollectionInLoopCheck.ERROR_MESSAGE, + description = AvoidGettingSizeCollectionInLoopCheck.ERROR_MESSAGE, priority = Priority.MINOR, tags = {"eco-design", "ecocode", "bad-practice", "performance"} ) -public class AvoidGettingSizeCollectionInForLoopCheck extends PHPSubscriptionCheck { +public class AvoidGettingSizeCollectionInLoopCheck extends PHPSubscriptionCheck { public static final String RULE_KEY = "EC3"; public static final String ERROR_MESSAGE = "Avoid getting the size of the collection in the loop"; diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopTest.java similarity index 53% rename from php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopTest.java rename to php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopTest.java index 9e527c140..85de2bdc4 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInForLoopTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopTest.java @@ -6,10 +6,10 @@ import java.io.File; -public class AvoidGettingSizeCollectionInForLoopTest { +public class AvoidGettingSizeCollectionInLoopTest { @Test public void test() throws Exception { - PHPCheckTest.check(new AvoidGettingSizeCollectionInForLoopCheck(), new PhpTestFile(new File("src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php"))); + PHPCheckTest.check(new AvoidGettingSizeCollectionInLoopCheck(), new PhpTestFile(new File("src/test/resources/checks/AvoidGettingSizeCollectionInLoop.php"))); } } diff --git a/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php b/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInLoop.php similarity index 100% rename from php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInForLoop.php rename to php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInLoop.php From d7f7c9c57673ac6af423e3bc7960f608baa9a957 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Thu, 1 Jun 2023 15:20:09 +0200 Subject: [PATCH 076/170] improving php CS --- .../php/checks/AvoidDoubleQuoteCheckTest.java | 2 +- ...allyCheckNOKfailsAllTryStatementsTest.java | 2 +- .../php/checks/IncrementCheckTest.java | 2 +- ...oFunctionCallWhenDeclaringForLoopTest.java | 2 +- .../UseOfMethodsForBasicOperationsTest.java | 2 +- ...idDoubleQuote.php => AvoidDoubleQuote.php} | 16 +---- .../resources/checks/AvoidFullSQLRequest.php | 19 ++--- .../checks/AvoidSQLRequestInLoop.php | 70 ++++++++++--------- ...inallyCheck_NOK_FailsAllTryStatements.php} | 1 - .../checks/AvoidUsingGlobalVariablesCheck.php | 6 +- .../test/resources/checks/IncrementCheck.php | 10 +++ ...=> NoFunctionCallWhenDeclaringForLoop.php} | 9 +-- ...php => UseOfMethodsForBasicOperations.php} | 7 +- .../test/resources/checks/incrementCheck.php | 16 ----- 14 files changed, 73 insertions(+), 91 deletions(-) rename php-plugin/src/test/resources/checks/{avoidDoubleQuote.php => AvoidDoubleQuote.php} (73%) rename php-plugin/src/test/resources/checks/{avoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php => AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php} (99%) create mode 100644 php-plugin/src/test/resources/checks/IncrementCheck.php rename php-plugin/src/test/resources/checks/{noFunctionCallWhenDeclaringForLoop.php => NoFunctionCallWhenDeclaringForLoop.php} (85%) rename php-plugin/src/test/resources/checks/{useOfMethodsForBasicOperations.php => UseOfMethodsForBasicOperations.php} (85%) delete mode 100644 php-plugin/src/test/resources/checks/incrementCheck.php diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheckTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheckTest.java index 1bd7f2ddb..9a68f8ac3 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheckTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheckTest.java @@ -10,7 +10,7 @@ public class AvoidDoubleQuoteCheckTest { @Test public void test() throws Exception { - PHPCheckTest.check(new AvoidDoubleQuoteCheck(), new PhpTestFile(new File("src/test/resources/checks/avoidDoubleQuote.php"))); + PHPCheckTest.check(new AvoidDoubleQuoteCheck(), new PhpTestFile(new File("src/test/resources/checks/AvoidDoubleQuote.php"))); } } diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheckNOKfailsAllTryStatementsTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheckNOKfailsAllTryStatementsTest.java index 7a14288ce..d9867e9f1 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheckNOKfailsAllTryStatementsTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheckNOKfailsAllTryStatementsTest.java @@ -10,7 +10,7 @@ public class AvoidTryCatchFinallyCheckNOKfailsAllTryStatementsTest { @Test public void test() throws Exception { - PHPCheckTest.check(new AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements(), new PhpTestFile(new File("src/test/resources/checks/avoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php"))); + PHPCheckTest.check(new AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements(), new PhpTestFile(new File("src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php"))); } } diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/IncrementCheckTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/IncrementCheckTest.java index 777531563..08e364ab2 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/IncrementCheckTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/IncrementCheckTest.java @@ -32,7 +32,7 @@ public class IncrementCheckTest { @Test public void test() throws Exception { - PHPCheckTest.check(new IncrementCheck(), new PhpTestFile(new File("src/test/resources/checks/incrementCheck.php"))); + PHPCheckTest.check(new IncrementCheck(), new PhpTestFile(new File("src/test/resources/checks/IncrementCheck.php"))); } } diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoopTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoopTest.java index 2f47ad768..2d18b0646 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoopTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoopTest.java @@ -10,6 +10,6 @@ public class NoFunctionCallWhenDeclaringForLoopTest { @Test public void test() throws Exception { - PHPCheckTest.check(new NoFunctionCallWhenDeclaringForLoop(), new PhpTestFile(new File("src/test/resources/checks/noFunctionCallWhenDeclaringForLoop.php"))); + PHPCheckTest.check(new NoFunctionCallWhenDeclaringForLoop(), new PhpTestFile(new File("src/test/resources/checks/NoFunctionCallWhenDeclaringForLoop.php"))); } } diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperationsTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperationsTest.java index ba878b1b6..1627d94a4 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperationsTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperationsTest.java @@ -10,6 +10,6 @@ public class UseOfMethodsForBasicOperationsTest { @Test public void test() throws Exception { - PHPCheckTest.check(new UseOfMethodsForBasicOperations(), new PhpTestFile(new File("src/test/resources/checks/useOfMethodsForBasicOperations.php"))); + PHPCheckTest.check(new UseOfMethodsForBasicOperations(), new PhpTestFile(new File("src/test/resources/checks/UseOfMethodsForBasicOperations.php"))); } } diff --git a/php-plugin/src/test/resources/checks/avoidDoubleQuote.php b/php-plugin/src/test/resources/checks/AvoidDoubleQuote.php similarity index 73% rename from php-plugin/src/test/resources/checks/avoidDoubleQuote.php rename to php-plugin/src/test/resources/checks/AvoidDoubleQuote.php index dd9b9da96..b8520a9bb 100644 --- a/php-plugin/src/test/resources/checks/avoidDoubleQuote.php +++ b/php-plugin/src/test/resources/checks/AvoidDoubleQuote.php @@ -4,21 +4,11 @@ $age = 19; $isStudent = true; $cours = array('physique','chimie','informatique','philosophie'); - $oneStudent = new Student(); - - - $lastName = 'Hugo'; - $age = 19; echo $lastName; + echo $name; echo '
      '; - echo $age; - - $lastName = 'Hadrien'; - $age = 18; - - echo $lastName; - echo "
      ";// NOK {{Avoid using double quote ("), prefer using simple quote (')}} + echo "
      "; // NOK {{Avoid using double quote ("), prefer using simple quote (')}} echo $age; $identite = $lastName .' '. $name; @@ -31,5 +21,3 @@ myFunction('name', 'age', 'isStudent'); myFunction("name", 'age', "isStudent"); // NOK {{Avoid using double quote ("), prefer using simple quote (')}} - -?> \ No newline at end of file diff --git a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php b/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php index f32480b78..c67ab981a 100644 --- a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php +++ b/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php @@ -1,24 +1,25 @@ SqlCall("SeLeCt * FrOm table"); // NOK {{Don't use the query SELECT * FROM}} - OtherClass->SqlCall("SeLeCt DiStInCt * FrOm table"); // NOK {{Don't use the query SELECT * FROM}} - OtherClass->SqlCall("SeLeCt name FrOm table"); + OtherClass->SqlCall('SELECT * FROM'); // NOK {{Don't use the query SELECT * FROM}} + OtherClass->SqlCall('SELECT DISTINCT * FROM'); // NOK {{Don't use the query SELECT * FROM}} + OtherClass->SqlCall('SELECT name FROM'); } public function PasseAsVariable() { - $sqlQuery1 = "SeLeCt * FrOm table"; // NOK {{Don't use the query SELECT * FROM}} - $sqlQuery2 = "SeLeCt DiStInCt * FrOm table"; // NOK {{Don't use the query SELECT * FROM}} - $sqlQuery3 = "SeLeCt name FrOm table"; + $sqlQuery1 = "SELECT * FROM"; // NOK {{Don't use the query SELECT * FROM}} + $sqlQuery2 = "SELECT DISTINCT * FROM"; // NOK {{Don't use the query SELECT * FROM}} + $sqlQuery3 = "SELECT name FROM"; OtherClass->SqlCall($sqlQuery1); OtherClass->SqlCall($sqlQuery2); + OtherClass->SqlCall($sqlQuery3); } } \ No newline at end of file diff --git a/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php b/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php index 8a1fb1293..c88e6d1c6 100644 --- a/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php +++ b/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php @@ -2,72 +2,74 @@ class AvoidFullSQLRequest { - private $DbUser = 'user'; - private $DbName = 'name'; - private $DbPass = 'pass'; - private $DbHost = 'host'; - private $Query = 'SELECT * FROM Table'; - private $OtherQuery = 'SELECT name FROM User'; - private $Connection; + private $dbUser = 'user'; + private $dbName = 'name'; + private $dbPass = 'pass'; + private $dbHost = 'host'; + private $query = 'SELECT * FROM Table'; + private $otherQuery = 'SELECT name FROM User'; + private $connection; - public function LaunchSQLRequest($someCondition) + public function launchSQLRequest($someCondition) { $expectedNbOfRequest = 5; - $arrayOfQuery = array($Query,$Query,$Query,$Query,$Query); - $this->Init(); - $this->NoLoop(); - $this->ForLoop($expectedNbOfRequest, $someCondition); - $this->ForEachLoop($arrayOfQuery, $someCondition); - $this->WhileLoop($expectedNbOfRequest, $someCondition); + $arrayOfQuery = array($this->query, $this->query, $this->query, $this->query, $this->query); + $this->init(); + $this->noLoop(); + $this->forLoop($expectedNbOfRequest, $someCondition); + $this->forEachLoop($arrayOfQuery, $someCondition); + $this->whileLoop($expectedNbOfRequest, $someCondition); } - private function Init() + private function init() { - $this->Connection = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'"); - mysql_select_db($dbname) or die("Could not open the db '$dbname'"); + $this->connection = mysqli_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("Unable to Connect to '$this->dbHost'"); + mysqli_select_db($this->connection, $this->dbName) or die("Could not open the db '$this->dbName'"); } - private function NoLoop() + private function noLoop() { - $result = mysql_query($this->Query); + $result = mysqli_query($this->connection, $this->query); // display result or work with it } - private function ForLoop($expectedNbOfRequest, $someCondition) + private function forLoop($expectedNbOfRequest, $someCondition) { for($index = 0; $expectedNbOfRequest > $index; ++$index){ - $result = mysql_query($this->Query); // NOK {{Avoid SQL request in loop}} + $result = mysqli_query($this->connection, $this->query); // NOK {{Avoid SQL request in loop}} // display result or work with it if($someCondition) { - $result = mysql_query($OtherQuery); // NOK {{Avoid SQL request in loop}} - $result = mysql_query($OtherQuery); // NOK {{Avoid SQL request in loop}} + $result = mysqli_query($this->connection, $this->otherQuery); // NOK {{Avoid SQL request in loop}} + $result = mysqli_query($this->connection, $this->otherQuery); // NOK {{Avoid SQL request in loop}} } } } - private function ForEachLoop($arrayOfQuery, $someCondition) + private function forEachLoop($arrayOfQuery, $someCondition) { foreach($arrayOfQuery as $query){ - $result = mysql_query($Query); // NOK {{Avoid SQL request in loop}} + $result = mysqli_query($this->connection, $query); // NOK {{Avoid SQL request in loop}} // display result or work with it - if($someCondition) - $result = mysql_query($OtherQuery); // NOK {{Avoid SQL request in loop}} + if($someCondition) { + $result = mysqli_query($this->connection, $query); // NOK {{Avoid SQL request in loop}} + } } } - private function WhileLoop($expectedNbOfRequest, $someCondition) + private function whileLoop($expectedNbOfRequest, $someCondition) { $nbOfRequest = 0; - do{ - $result = mysql_query($this->Query); // NOK {{Avoid SQL request in loop}} + do { + $result = mysqli_query($this->connection, $this->query); // NOK {{Avoid SQL request in loop}} // display result or work with it - if($someCondition) - $result = mysql_query($OtherQuery); // NOK {{Avoid SQL request in loop}} + if($someCondition) { + $result = mysqli_query($this->connection, $this->otherQuery); // NOK {{Avoid SQL request in loop}} + } ++$nbOfRequest; - }while($expectedNbOfRequest > $nbOfRequest); + } while($expectedNbOfRequest > $nbOfRequest); } - private function EmptyLoop() + private function emptyLoop() { for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); } diff --git a/php-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php b/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php similarity index 99% rename from php-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php rename to php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php index 1698df424..577c1ea29 100644 --- a/php-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php +++ b/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php @@ -34,4 +34,3 @@ function test() { echo $e->getMessage()." catch in\n"; throw $e; }*/ -?> diff --git a/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php b/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php index 2f5d4eadb..95f422943 100644 --- a/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php +++ b/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php @@ -1,4 +1,5 @@ + +function somme3($a, $b) { // Compliant + return $a + $b; +} \ No newline at end of file diff --git a/php-plugin/src/test/resources/checks/IncrementCheck.php b/php-plugin/src/test/resources/checks/IncrementCheck.php new file mode 100644 index 000000000..0f1fb659e --- /dev/null +++ b/php-plugin/src/test/resources/checks/IncrementCheck.php @@ -0,0 +1,10 @@ + diff --git a/php-plugin/src/test/resources/checks/useOfMethodsForBasicOperations.php b/php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php similarity index 85% rename from php-plugin/src/test/resources/checks/useOfMethodsForBasicOperations.php rename to php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php index daf07b62a..3c45dfaa8 100644 --- a/php-plugin/src/test/resources/checks/useOfMethodsForBasicOperations.php +++ b/php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php @@ -2,7 +2,6 @@ min(4, 2); // NOK {{Use of methods for basic operations}} minWithBasic(4, 2); - minWithAutoImplement(4,2); class Obj { @@ -11,8 +10,6 @@ function minWithBasic($a, $b) { } function minWithAutoImplement($a, $b) { - return ($a < $b) ? $a : $b; + return ($a < $b) ? $a : $b; // Compliant } -}; - -?> \ No newline at end of file +} diff --git a/php-plugin/src/test/resources/checks/incrementCheck.php b/php-plugin/src/test/resources/checks/incrementCheck.php deleted file mode 100644 index 8aced9e59..000000000 --- a/php-plugin/src/test/resources/checks/incrementCheck.php +++ /dev/null @@ -1,16 +0,0 @@ - \ No newline at end of file From 77b91fa76464e3b3a79c01469e93fb0fafbc92af Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Thu, 1 Jun 2023 16:35:58 +0200 Subject: [PATCH 077/170] improving php CS --- .../l10n/php/rules/custom/EC22.html | 2 +- .../resources/checks/AvoidFullSQLRequest.php | 6 +- .../checks/AvoidSQLRequestInLoop.php | 126 +++++++++--------- ...FinallyCheck_NOK_FailsAllTryStatements.php | 13 +- .../checks/AvoidUsingGlobalVariablesCheck.php | 3 +- .../NoFunctionCallWhenDeclaringForLoop.php | 3 +- .../checks/UseOfMethodsForBasicOperations.php | 5 +- 7 files changed, 76 insertions(+), 82 deletions(-) diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC22.html b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC22.html index f5d6da36f..0294f0a03 100644 --- a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC22.html +++ b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC22.html @@ -5,5 +5,5 @@

      Noncompliant Code Example

      Compliant Solution

      -	$min = ($a < $b) ? $a : $b;
      +	$min = $a < $b ? $a : $b;
       
      diff --git a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php b/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php index c67ab981a..33b8c024c 100644 --- a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php +++ b/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php @@ -6,15 +6,13 @@ class AvoidFullSQLRequest { - public function LiteralString() - { + public function literalString() { OtherClass->SqlCall('SELECT * FROM'); // NOK {{Don't use the query SELECT * FROM}} OtherClass->SqlCall('SELECT DISTINCT * FROM'); // NOK {{Don't use the query SELECT * FROM}} OtherClass->SqlCall('SELECT name FROM'); } - public function PasseAsVariable() - { + public function passeAsVariable() { $sqlQuery1 = "SELECT * FROM"; // NOK {{Don't use the query SELECT * FROM}} $sqlQuery2 = "SELECT DISTINCT * FROM"; // NOK {{Don't use the query SELECT * FROM}} $sqlQuery3 = "SELECT name FROM"; diff --git a/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php b/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php index c88e6d1c6..52cdb10a7 100644 --- a/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php +++ b/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php @@ -2,75 +2,73 @@ class AvoidFullSQLRequest { - private $dbUser = 'user'; - private $dbName = 'name'; - private $dbPass = 'pass'; - private $dbHost = 'host'; - private $query = 'SELECT * FROM Table'; - private $otherQuery = 'SELECT name FROM User'; - private $connection; + private $DbUser = 'user'; + private $DbName = 'name'; + private $DbPass = 'pass'; + private $DbHost = 'host'; + private $Query = 'SELECT * FROM Table'; + private $OtherQuery = 'SELECT name FROM User'; + private $Connection; - public function launchSQLRequest($someCondition) - { - $expectedNbOfRequest = 5; - $arrayOfQuery = array($this->query, $this->query, $this->query, $this->query, $this->query); - $this->init(); - $this->noLoop(); - $this->forLoop($expectedNbOfRequest, $someCondition); - $this->forEachLoop($arrayOfQuery, $someCondition); - $this->whileLoop($expectedNbOfRequest, $someCondition); - } - private function init() - { - $this->connection = mysqli_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("Unable to Connect to '$this->dbHost'"); - mysqli_select_db($this->connection, $this->dbName) or die("Could not open the db '$this->dbName'"); - } - - private function noLoop() - { - $result = mysqli_query($this->connection, $this->query); - // display result or work with it - } + public function LaunchSQLRequest($someCondition) + { + $expectedNbOfRequest = 5; + $arrayOfQuery = array($Query,$Query,$Query,$Query,$Query); + $this->Init(); + $this->NoLoop(); + $this->ForLoop($expectedNbOfRequest, $someCondition); + $this->ForEachLoop($arrayOfQuery, $someCondition); + $this->WhileLoop($expectedNbOfRequest, $someCondition); + } + private function Init() + { + $this->Connection = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'"); + mysql_select_db($dbname) or die("Could not open the db '$dbname'"); + } - private function forLoop($expectedNbOfRequest, $someCondition) - { - for($index = 0; $expectedNbOfRequest > $index; ++$index){ - $result = mysqli_query($this->connection, $this->query); // NOK {{Avoid SQL request in loop}} - // display result or work with it - if($someCondition) - { - $result = mysqli_query($this->connection, $this->otherQuery); // NOK {{Avoid SQL request in loop}} - $result = mysqli_query($this->connection, $this->otherQuery); // NOK {{Avoid SQL request in loop}} - } - } - } + private function NoLoop() + { + $result = mysql_query($this->Query); + // display result or work with it + } - private function forEachLoop($arrayOfQuery, $someCondition) - { - foreach($arrayOfQuery as $query){ - $result = mysqli_query($this->connection, $query); // NOK {{Avoid SQL request in loop}} - // display result or work with it - if($someCondition) { - $result = mysqli_query($this->connection, $query); // NOK {{Avoid SQL request in loop}} + private function ForLoop($expectedNbOfRequest, $someCondition) + { + for($index = 0; $expectedNbOfRequest > $index; ++$index){ + $result = mysql_query($this->Query); // NOK {{Avoid SQL request in loop}} + // display result or work with it + if($someCondition) + { + $result = mysql_query($OtherQuery); // NOK {{Avoid SQL request in loop}} + $result = mysql_query($OtherQuery); // NOK {{Avoid SQL request in loop}} } - } - } + } + } - private function whileLoop($expectedNbOfRequest, $someCondition) - { - $nbOfRequest = 0; - do { - $result = mysqli_query($this->connection, $this->query); // NOK {{Avoid SQL request in loop}} - // display result or work with it - if($someCondition) { - $result = mysqli_query($this->connection, $this->otherQuery); // NOK {{Avoid SQL request in loop}} - } - ++$nbOfRequest; - } while($expectedNbOfRequest > $nbOfRequest); - } + private function ForEachLoop($arrayOfQuery, $someCondition) + { + foreach($arrayOfQuery as $query){ + $result = mysql_query($Query); // NOK {{Avoid SQL request in loop}} + // display result or work with it + if($someCondition) + $result = mysql_query($OtherQuery); // NOK {{Avoid SQL request in loop}} + } + } + + private function WhileLoop($expectedNbOfRequest, $someCondition) + { + $nbOfRequest = 0; + do{ + $result = mysql_query($this->Query); // NOK {{Avoid SQL request in loop}} + // display result or work with it + if($someCondition) + $result = mysql_query($OtherQuery); // NOK {{Avoid SQL request in loop}} + ++$nbOfRequest; + }while($expectedNbOfRequest > $nbOfRequest); + } - private function emptyLoop() + private function EmptyLoop() { - for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); - } + for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); + } } \ No newline at end of file diff --git a/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php b/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php index 577c1ea29..350f55c8e 100644 --- a/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php +++ b/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php @@ -7,14 +7,11 @@ function test() { throw new SpecificException('Oopsie'); } -try // NOK {{Avoid using try-catch}} -{ - $picture = PDF_open_image_file($PDF, "jpeg", $imgFile, "", 0); // This is the original statement, this works on PHP4 -} -catch(Exception $ex) -{ - $msg = "Error opening $imgFile for Product $row['Identifier']"; - throw new Exception($msg); +try { // NOK {{Avoid using try-catch}} + $picture = PDF_open_image_file($PDF, "jpeg", $imgFile, "", 0); // This is the original statement, this works on PHP4 +} catch(Exception $ex) { + $msg = "Error opening $imgFile for Product $row['Identifier']"; + throw new Exception($msg); } try { // NOK {{Avoid using try-catch}} diff --git a/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php b/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php index 95f422943..4b7d2a6dc 100644 --- a/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php +++ b/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php @@ -17,4 +17,5 @@ function somme2() { // NOK {{Prefer local variables to globals}} function somme3($a, $b) { // Compliant return $a + $b; -} \ No newline at end of file +} +echo somme3($a, $b); diff --git a/php-plugin/src/test/resources/checks/NoFunctionCallWhenDeclaringForLoop.php b/php-plugin/src/test/resources/checks/NoFunctionCallWhenDeclaringForLoop.php index 61cbfa8e5..9e0b144fe 100644 --- a/php-plugin/src/test/resources/checks/NoFunctionCallWhenDeclaringForLoop.php +++ b/php-plugin/src/test/resources/checks/NoFunctionCallWhenDeclaringForLoop.php @@ -30,8 +30,7 @@ for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); // NOK {{Do not call a function in for-type loop declaration}} -function somewhat_calcMax() -{ +function somewhat_calcMax() { return 500; } diff --git a/php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php b/php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php index 3c45dfaa8..4f89ca4af 100644 --- a/php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php +++ b/php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php @@ -4,12 +4,13 @@ minWithBasic(4, 2); minWithAutoImplement(4,2); -class Obj { +class Obj +{ function minWithBasic($a, $b) { return min($a, $b); // NOK {{Use of methods for basic operations}} } function minWithAutoImplement($a, $b) { - return ($a < $b) ? $a : $b; // Compliant + return $a < $b ? $a : $b; // Compliant } } From 8835e477fdce95ceff2790ab0b8d91a01a349c92 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Thu, 1 Jun 2023 16:35:58 +0200 Subject: [PATCH 078/170] improving php CS --- .../checks/AvoidSQLRequestInLoop.php | 99 +++++++++---------- 1 file changed, 49 insertions(+), 50 deletions(-) diff --git a/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php b/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php index 52cdb10a7..d37f5c877 100644 --- a/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php +++ b/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php @@ -2,73 +2,72 @@ class AvoidFullSQLRequest { - private $DbUser = 'user'; - private $DbName = 'name'; - private $DbPass = 'pass'; - private $DbHost = 'host'; - private $Query = 'SELECT * FROM Table'; - private $OtherQuery = 'SELECT name FROM User'; - private $Connection; - - public function LaunchSQLRequest($someCondition) - { + private $dbUser = 'user'; + private $dbName = 'name'; + private $dbPass = 'pass'; + private $dbHost = 'host'; + private $query = 'SELECT * FROM Table'; + private $otherQuery = 'SELECT name FROM User'; + private $connection; + public function launchSQLRequest($someCondition) { $expectedNbOfRequest = 5; - $arrayOfQuery = array($Query,$Query,$Query,$Query,$Query); - $this->Init(); - $this->NoLoop(); - $this->ForLoop($expectedNbOfRequest, $someCondition); - $this->ForEachLoop($arrayOfQuery, $someCondition); - $this->WhileLoop($expectedNbOfRequest, $someCondition); + $arrayOfQuery = array($this->query, $this->query, $this->query, $this->query, $this->query); + $this->init(); + $this->noLoop(); + $this->forLoop($expectedNbOfRequest, $someCondition); + $this->forEachLoop($arrayOfQuery, $someCondition); + $this->whileLoop($expectedNbOfRequest, $someCondition); + $this->emptyLoop(); } - private function Init() - { - $this->Connection = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'"); - mysql_select_db($dbname) or die("Could not open the db '$dbname'"); + private function init() { + $this->connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("Unable to Connect to '$dbhost'"); + mysql_select_db($this->dbName) or die("Could not open the db '$this->dbName'"); } - private function NoLoop() - { - $result = mysql_query($this->Query); - // display result or work with it + private function noLoop() { + $result = mysql_query($this->query); + echo $result; } - private function ForLoop($expectedNbOfRequest, $someCondition) - { - for($index = 0; $expectedNbOfRequest > $index; ++$index){ - $result = mysql_query($this->Query); // NOK {{Avoid SQL request in loop}} - // display result or work with it - if($someCondition) - { - $result = mysql_query($OtherQuery); // NOK {{Avoid SQL request in loop}} - $result = mysql_query($OtherQuery); // NOK {{Avoid SQL request in loop}} + private function forLoop($expectedNbOfRequest, $someCondition) { + for ($index = 0; $expectedNbOfRequest > $index; ++$index) { + $result = mysql_query($this->query); // NOK {{Avoid SQL request in loop}} + + if ($someCondition) { + $result = mysql_query($this->otherQuery); // NOK {{Avoid SQL request in loop}} } + + echo $result; } } - private function ForEachLoop($arrayOfQuery, $someCondition) - { - foreach($arrayOfQuery as $query){ - $result = mysql_query($Query); // NOK {{Avoid SQL request in loop}} - // display result or work with it - if($someCondition) - $result = mysql_query($OtherQuery); // NOK {{Avoid SQL request in loop}} + private function forEachLoop($arrayOfQuery, $someCondition) { + foreach ($arrayOfQuery as $query) { + $result = mysql_query($query); // NOK {{Avoid SQL request in loop}} + + if ($someCondition) { + $result = mysql_query($this->otherQuery); // NOK {{Avoid SQL request in loop}} + } + + echo $result; } } - private function WhileLoop($expectedNbOfRequest, $someCondition) - { + private function whileLoop($expectedNbOfRequest, $someCondition) { $nbOfRequest = 0; - do{ - $result = mysql_query($this->Query); // NOK {{Avoid SQL request in loop}} - // display result or work with it - if($someCondition) - $result = mysql_query($OtherQuery); // NOK {{Avoid SQL request in loop}} + do { + $result = mysql_query($this->query); // NOK {{Avoid SQL request in loop}} + + if($someCondition) { + $result = mysql_query($this->otherQuery); // NOK {{Avoid SQL request in loop}} + } + + echo $result; ++$nbOfRequest; - }while($expectedNbOfRequest > $nbOfRequest); + } while ($expectedNbOfRequest > $nbOfRequest); } - private function EmptyLoop() - { + private function emptyLoop() { for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); } } \ No newline at end of file From 54ce8605cfc7e85b97bbc40c70b9a5da3b859f06 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Fri, 2 Jun 2023 10:40:24 +0200 Subject: [PATCH 079/170] linting with php-cs-fixer --- .../resources/checks/AvoidDoubleQuote.php | 33 ++++++++++--------- .../resources/checks/AvoidFullSQLRequest.php | 24 +++++++------- .../checks/AvoidSQLRequestInLoop.php | 23 ++++++++----- ...FinallyCheck_NOK_FailsAllTryStatements.php | 29 ++++++++++------ .../checks/AvoidUsingGlobalVariablesCheck.php | 12 +++++-- .../test/resources/checks/IncrementCheck.php | 7 ++-- .../NoFunctionCallWhenDeclaringForLoop.php | 8 +++-- .../checks/UseOfMethodsForBasicOperations.php | 8 +++-- 8 files changed, 88 insertions(+), 56 deletions(-) diff --git a/php-plugin/src/test/resources/checks/AvoidDoubleQuote.php b/php-plugin/src/test/resources/checks/AvoidDoubleQuote.php index b8520a9bb..30e0a4795 100644 --- a/php-plugin/src/test/resources/checks/AvoidDoubleQuote.php +++ b/php-plugin/src/test/resources/checks/AvoidDoubleQuote.php @@ -1,23 +1,24 @@ '; - echo "
      "; // NOK {{Avoid using double quote ("), prefer using simple quote (')}} - echo $age; +$lastName = 'Hugo'; +$name = "Hamon"; // NOK {{Avoid using double quote ("), prefer using simple quote (')}} +$age = 19; +$isStudent = true; +$cours = array('physique','chimie','informatique','philosophie'); - $identite = $lastName .' '. $name; - echo $identite; +echo $lastName; +echo $name; +echo '
      '; +echo "
      "; // NOK {{Avoid using double quote ("), prefer using simple quote (')}} +echo $age; - myFunction($name, $age, $isStudent); +$identite = $lastName .' '. $name; +echo $identite; - myFunction("name", "age", "isStudent"); // NOK {{Avoid using double quote ("), prefer using simple quote (')}} +myFunction($name, $age, $isStudent); - myFunction('name', 'age', 'isStudent'); +myFunction("name", "age", "isStudent"); // NOK {{Avoid using double quote ("), prefer using simple quote (')}} - myFunction("name", 'age', "isStudent"); // NOK {{Avoid using double quote ("), prefer using simple quote (')}} +myFunction('name', 'age', 'isStudent'); + +myFunction("name", 'age', "isStudent"); // NOK {{Avoid using double quote ("), prefer using simple quote (')}} diff --git a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php b/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php index 33b8c024c..90e9907fb 100644 --- a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php +++ b/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php @@ -6,18 +6,20 @@ class AvoidFullSQLRequest { - public function literalString() { - OtherClass->SqlCall('SELECT * FROM'); // NOK {{Don't use the query SELECT * FROM}} - OtherClass->SqlCall('SELECT DISTINCT * FROM'); // NOK {{Don't use the query SELECT * FROM}} - OtherClass->SqlCall('SELECT name FROM'); - } + public function literalString() + { + OtherClass->SqlCall('SELECT * FROM'); // NOK {{Don't use the query SELECT * FROM}} + OtherClass->SqlCall('SELECT DISTINCT * FROM'); // NOK {{Don't use the query SELECT * FROM}} + OtherClass->SqlCall('SELECT name FROM'); + } - public function passeAsVariable() { + public function passeAsVariable() + { $sqlQuery1 = "SELECT * FROM"; // NOK {{Don't use the query SELECT * FROM}} $sqlQuery2 = "SELECT DISTINCT * FROM"; // NOK {{Don't use the query SELECT * FROM}} $sqlQuery3 = "SELECT name FROM"; - OtherClass->SqlCall($sqlQuery1); - OtherClass->SqlCall($sqlQuery2); - OtherClass->SqlCall($sqlQuery3); - } -} \ No newline at end of file + OtherClass->SqlCall($sqlQuery1); + OtherClass->SqlCall($sqlQuery2); + OtherClass->SqlCall($sqlQuery3); + } +} diff --git a/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php b/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php index d37f5c877..5a804bbdf 100644 --- a/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php +++ b/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php @@ -9,7 +9,8 @@ class AvoidFullSQLRequest private $query = 'SELECT * FROM Table'; private $otherQuery = 'SELECT name FROM User'; private $connection; - public function launchSQLRequest($someCondition) { + public function launchSQLRequest($someCondition) + { $expectedNbOfRequest = 5; $arrayOfQuery = array($this->query, $this->query, $this->query, $this->query, $this->query); $this->init(); @@ -19,17 +20,20 @@ public function launchSQLRequest($someCondition) { $this->whileLoop($expectedNbOfRequest, $someCondition); $this->emptyLoop(); } - private function init() { + private function init() + { $this->connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("Unable to Connect to '$dbhost'"); mysql_select_db($this->dbName) or die("Could not open the db '$this->dbName'"); } - private function noLoop() { + private function noLoop() + { $result = mysql_query($this->query); echo $result; } - private function forLoop($expectedNbOfRequest, $someCondition) { + private function forLoop($expectedNbOfRequest, $someCondition) + { for ($index = 0; $expectedNbOfRequest > $index; ++$index) { $result = mysql_query($this->query); // NOK {{Avoid SQL request in loop}} @@ -41,7 +45,8 @@ private function forLoop($expectedNbOfRequest, $someCondition) { } } - private function forEachLoop($arrayOfQuery, $someCondition) { + private function forEachLoop($arrayOfQuery, $someCondition) + { foreach ($arrayOfQuery as $query) { $result = mysql_query($query); // NOK {{Avoid SQL request in loop}} @@ -53,7 +58,8 @@ private function forEachLoop($arrayOfQuery, $someCondition) { } } - private function whileLoop($expectedNbOfRequest, $someCondition) { + private function whileLoop($expectedNbOfRequest, $someCondition) + { $nbOfRequest = 0; do { $result = mysql_query($this->query); // NOK {{Avoid SQL request in loop}} @@ -67,7 +73,8 @@ private function whileLoop($expectedNbOfRequest, $someCondition) { } while ($expectedNbOfRequest > $nbOfRequest); } - private function emptyLoop() { + private function emptyLoop() + { for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); } -} \ No newline at end of file +} diff --git a/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php b/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php index 350f55c8e..a3835e862 100644 --- a/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php +++ b/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php @@ -1,26 +1,35 @@ - getMessage()." catch in\n"; +} catch (\Exception $e) { + echo $e->getMessage() . " catch in\n"; throw $e; } finally { - echo $e->getMessage()." finally \n"; + echo $e->getMessage() . " finally \n"; throw new \Exception("Bye"); } diff --git a/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php b/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php index 4b7d2a6dc..e3a1eb4dd 100644 --- a/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php +++ b/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php @@ -2,20 +2,26 @@ $a = 1; $b = 2; -function somme() { // NOK {{Prefer local variables to globals}} +function somme() // NOK {{Prefer local variables to globals}} +{ $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; } + somme(); echo $b; -function somme2() { // NOK {{Prefer local variables to globals}} +function somme2() // NOK {{Prefer local variables to globals}} +{ global $a, $b; $b = $a + $b; } + somme2(); echo $b; -function somme3($a, $b) { // Compliant +function somme3($a, $b) // Compliant +{ return $a + $b; } + echo somme3($a, $b); diff --git a/php-plugin/src/test/resources/checks/IncrementCheck.php b/php-plugin/src/test/resources/checks/IncrementCheck.php index 0f1fb659e..16bfc6813 100644 --- a/php-plugin/src/test/resources/checks/IncrementCheck.php +++ b/php-plugin/src/test/resources/checks/IncrementCheck.php @@ -1,10 +1,13 @@ 10) { break; } @@ -30,7 +31,8 @@ for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); // NOK {{Do not call a function in for-type loop declaration}} -function somewhat_calcMax() { +function somewhat_calcMax() +{ return 500; } @@ -41,5 +43,5 @@ function somewhat_calcMax() { $maxI = somewhat_calcMax(); for ($i = 0; $i <= $maxI; $i++) { // COMPLIANT - var_dump($i); + var_dump($i); } diff --git a/php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php b/php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php index 4f89ca4af..b63555ec7 100644 --- a/php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php +++ b/php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php @@ -2,15 +2,17 @@ min(4, 2); // NOK {{Use of methods for basic operations}} minWithBasic(4, 2); -minWithAutoImplement(4,2); +minWithAutoImplement(4, 2); class Obj { - function minWithBasic($a, $b) { + public function minWithBasic($a, $b) + { return min($a, $b); // NOK {{Use of methods for basic operations}} } - function minWithAutoImplement($a, $b) { + public function minWithAutoImplement($a, $b) + { return $a < $b ? $a : $b; // Compliant } } From 4e96f2a6d10b7a656df197d966b5f3ee8edda615 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Fri, 2 Jun 2023 16:36:07 +0200 Subject: [PATCH 080/170] up and lint AvoidTryCatchFinallyCheck --- ...FinallyCheck_NOK_FailsAllTryStatements.php | 23 ++++++++----------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php b/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php index a3835e862..f10a79842 100644 --- a/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php +++ b/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php @@ -9,8 +9,8 @@ function test() throw new SpecificException('Oopsie'); } -$file = 'file'; try { // NOK {{Avoid using try-catch}} + $file = 'file'; $picture = PDF_open_image_file( pdf_new(), "jpeg", @@ -18,25 +18,20 @@ function test() "", 0 ); // This is the original statement, this works on PHP4 -} catch (Exception $ex) { - $msg = "Error opening $file"; - throw new \Exception($msg); +} catch (Exception $e) { + echo "Error opening $file : " . $e->getMessage(); } try { // NOK {{Avoid using try-catch}} - throw new \Exception("Hello"); -} catch (\Exception $e) { + throw new SpecificException("Hello"); +} catch (SpecificException $e) { echo $e->getMessage() . " catch in\n"; - throw $e; } finally { echo $e->getMessage() . " finally \n"; - throw new \Exception("Bye"); } -//FAILS with this RULE -/*try { +try { // NOK {{Avoid using try-catch}} throw new \Exception("Hello"); -} catch(\Exception $e) { - echo $e->getMessage()." catch in\n"; - throw $e; -}*/ +} catch (\Exception $e) { + echo $e->getMessage() . " catch in\n"; +} From 77b13892a039d34b0c9330e0223a579fd2e4af22 Mon Sep 17 00:00:00 2001 From: Aghiles Azzoug Date: Sat, 3 Jun 2023 12:26:23 +0200 Subject: [PATCH 081/170] refactor: update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 389c2abe0..89ad3482a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +- [#191](https://github.com/green-code-initiative/ecoCode/issues/191) update rule tags for Java, Python, and PHP plugins. ### Added - [#109](https://github.com/green-code-initiative/ecoCode/issues/109) PHP rule : **Getting the size of the collection in the loop**. For further [RULES.md](./RULES.md) file. From 6d8bbf46240772999d4fd1d65672f13a699764c2 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Mon, 5 Jun 2023 10:36:26 +0200 Subject: [PATCH 082/170] updating CHANGELOG.md --- CHANGELOG.md | 62 ++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 43 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 389c2abe0..25c7fcf44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,16 +8,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added -- [#109](https://github.com/green-code-initiative/ecoCode/issues/109) PHP rule : **Getting the size of the collection in the loop**. For further [RULES.md](./RULES.md) file. + +- [#109](https://github.com/green-code-initiative/ecoCode/issues/109) PHP rule : **Getting the size of the collection in + the loop**. For further [RULES.md](./RULES.md) file. - [#113](https://github.com/green-code-initiative/ecoCode/issues/113) new PYTHON rule : Use unoptimized vector images -- [#127](https://github.com/green-code-initiative/ecoCode/issues/127) Add Python rule EC404: Usage of generator comprehension instead of list comprehension in for loop declaration -- [#192](https://github.com/green-code-initiative/ecoCode/pull/192) Add Python rule EC203: Detect unoptimized file formats -- [#108](https://github.com/green-code-initiative/ecoCode/issues/108) Add Python rule EC66: Use single quote (') instead of quotation mark (") +- [#127](https://github.com/green-code-initiative/ecoCode/issues/127) Add Python rule EC404: Usage of generator + comprehension instead of list comprehension in for loop declaration +- [#192](https://github.com/green-code-initiative/ecoCode/pull/192) Add Python rule EC203: Detect unoptimized file + formats +- [#108](https://github.com/green-code-initiative/ecoCode/issues/108) Add Python rule EC66: Use single quote (') instead + of quotation mark (") ### Changed -- [#19](https://github.com/green-code-initiative/ecoCode-common/issues/19) process changed for development environment installation : easier to initialize locally environment (check [`INSTALL.md`](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment) file) +- [#19](https://github.com/green-code-initiative/ecoCode-common/issues/19) process changed for development environment + installation : easier to initialize locally environment ( + check [`INSTALL.md`](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment) + file) +- [#196](https://github.com/green-code-initiative/ecoCode/issues/196) updating PHP files to make them following the + coding standards (PSR-12) ### Deleted @@ -27,7 +37,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- [#180](https://github.com/green-code-initiative/ecoCode/pull/180) correction of SonarQube review for MarketPlace (sonar plugin) +- [#180](https://github.com/green-code-initiative/ecoCode/pull/180) correction of SonarQube review for MarketPlace ( + sonar plugin) ### Deleted @@ -35,7 +46,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- [#171](https://github.com/green-code-initiative/ecoCode/issues/171) Add migration mechanism to support "issue re-keying" +- [#171](https://github.com/green-code-initiative/ecoCode/issues/171) Add migration mechanism to support "issue + re-keying" ### Changed @@ -50,8 +62,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- [#63](https://github.com/green-code-initiative/ecoCode/issues/63) Update plugins to be compliant for SonarQube MarketPlace integration ( PR [#79](https://github.com/green-code-initiative/ecoCode/pull/79) ) -- [#88](https://github.com/green-code-initiative/ecoCode/pull/88) upgrade rules matrix with new ids + refactoring rules documentation (`RULES.md`) +- [#63](https://github.com/green-code-initiative/ecoCode/issues/63) Update plugins to be compliant for SonarQube + MarketPlace integration ( PR [#79](https://github.com/green-code-initiative/ecoCode/pull/79) ) +- [#88](https://github.com/green-code-initiative/ecoCode/pull/88) upgrade rules matrix with new ids + refactoring rules + documentation (`RULES.md`) ### Deleted @@ -67,14 +81,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- [#40](https://github.com/green-code-initiative/ecoCode/issues/40) Refactoring of package names (`cnumr` to `greencodeinitiative`) +- [#40](https://github.com/green-code-initiative/ecoCode/issues/40) Refactoring of package names (`cnumr` + to `greencodeinitiative`) - [#58](https://github.com/green-code-initiative/ecoCode/issues/58) check and upgrade compatibility to SonarQube 9.9 - move common init scripts to `ecoCode-common` repository -- modifying documentation and move `CONTRIBUTING.md`, `CODE_STYLE.md` and `INSTALL.md` to common doc in `ecoCode-common` repository -- security / performance optimizations : correction of `sonarcloud.io` security hotspots (java / php, python) and move Pattern compilation to static attribute -- [#65](https://github.com/green-code-initiative/ecoCode/issues/65) Create a test project to check new plugin rule in real environment -- [#71](https://github.com/green-code-initiative/ecoCode/issues/71) After an PHP analysis, no ecocode code smells appears in my Sonar project -- [#64](https://github.com/green-code-initiative/ecoCode/issues/64) Python: ecoCode plugin with SonarQube, no code-smell detection +- modifying documentation and move `CONTRIBUTING.md`, `CODE_STYLE.md` and `INSTALL.md` to common doc in `ecoCode-common` + repository +- security / performance optimizations : correction of `sonarcloud.io` security hotspots (java / php, python) and move + Pattern compilation to static attribute +- [#65](https://github.com/green-code-initiative/ecoCode/issues/65) Create a test project to check new plugin rule in + real environment +- [#71](https://github.com/green-code-initiative/ecoCode/issues/71) After an PHP analysis, no ecocode code smells + appears in my Sonar project +- [#64](https://github.com/green-code-initiative/ecoCode/issues/64) Python: ecoCode plugin with SonarQube, no code-smell + detection - [#55](https://github.com/green-code-initiative/ecoCode/issues/55) rename `eco-conception` tag of rules to `eco-design` - [#76](https://github.com/green-code-initiative/ecoCode/issues/76) correction of SonarQube plugins homepage link broken - documentation upgrade @@ -88,14 +108,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - [#23](https://github.com/green-code-initiative/ecoCode/pull/23) Add images to the description files. -- [#46](https://github.com/green-code-initiative/ecoCode/pull/46) Add CONTRIBUTING.MD, CODE_OF_CONDUCT.md and CODE_STYLE.md +- [#46](https://github.com/green-code-initiative/ecoCode/pull/46) Add CONTRIBUTING.MD, CODE_OF_CONDUCT.md and + CODE_STYLE.md ### Changed -- [#27](https://github.com/green-code-initiative/ecoCode/pull/27) Fix [WARNING] Maven-shade-plugin overlapping classes and upgrade SonarRuntime. +- [#27](https://github.com/green-code-initiative/ecoCode/pull/27) Fix [WARNING] Maven-shade-plugin overlapping classes + and upgrade SonarRuntime. - [#33](https://github.com/green-code-initiative/ecoCode/issues/33) Update plugin description in code -- [#42](https://github.com/green-code-initiative/ecoCode/issues/42) Fix Crash SonarQube analysis because of some ClassCast Exceptions -- [#48](https://github.com/green-code-initiative/ecoCode/pull/48) correction SONAR issue info - delete public keyword on tests +- [#42](https://github.com/green-code-initiative/ecoCode/issues/42) Fix Crash SonarQube analysis because of some + ClassCast Exceptions +- [#48](https://github.com/green-code-initiative/ecoCode/pull/48) correction SONAR issue info - delete public keyword on + tests - Improve "build" GitHub actions to execute checks on branches from fork repositories ## [0.2.1] - 2022-12-30 From 76f564b4ef13e5d62d133e8db76f57bf47cd063d Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Mon, 5 Jun 2023 16:43:11 +0200 Subject: [PATCH 083/170] unformat CHANGELOG.md --- CHANGELOG.md | 65 +++++++++++++++++----------------------------------- 1 file changed, 21 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ebf8bbab..207017de4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,26 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#191](https://github.com/green-code-initiative/ecoCode/issues/191) update rule tags for Java, Python, and PHP plugins. ### Added - -- [#109](https://github.com/green-code-initiative/ecoCode/issues/109) PHP rule : **Getting the size of the collection in - the loop**. For further [RULES.md](./RULES.md) file. +- [#109](https://github.com/green-code-initiative/ecoCode/issues/109) PHP rule : **Getting the size of the collection in the loop**. For further [RULES.md](./RULES.md) file. - [#113](https://github.com/green-code-initiative/ecoCode/issues/113) new PYTHON rule : Use unoptimized vector images -- [#127](https://github.com/green-code-initiative/ecoCode/issues/127) Add Python rule EC404: Usage of generator - comprehension instead of list comprehension in for loop declaration -- [#192](https://github.com/green-code-initiative/ecoCode/pull/192) Add Python rule EC203: Detect unoptimized file - formats -- [#108](https://github.com/green-code-initiative/ecoCode/issues/108) Add Python rule EC66: Use single quote (') instead - of quotation mark (") +- [#127](https://github.com/green-code-initiative/ecoCode/issues/127) Add Python rule EC404: Usage of generator comprehension instead of list comprehension in for loop declaration +- [#192](https://github.com/green-code-initiative/ecoCode/pull/192) Add Python rule EC203: Detect unoptimized file formats +- [#108](https://github.com/green-code-initiative/ecoCode/issues/108) Add Python rule EC66: Use single quote (') instead of quotation mark (") ### Changed -- [#19](https://github.com/green-code-initiative/ecoCode-common/issues/19) process changed for development environment - installation : easier to initialize locally environment ( - check [`INSTALL.md`](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment) - file) -- [#196](https://github.com/green-code-initiative/ecoCode/issues/196) updating PHP files to make them following the - coding standards (PSR-12) +- [#19](https://github.com/green-code-initiative/ecoCode-common/issues/19) process changed for development environment installation : easier to initialize locally environment (check [`INSTALL.md`](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment) file) +- [#196](https://github.com/green-code-initiative/ecoCode/issues/196) updating PHP files to make them following the coding standards (PSR-12) ### Deleted @@ -38,8 +29,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- [#180](https://github.com/green-code-initiative/ecoCode/pull/180) correction of SonarQube review for MarketPlace ( - sonar plugin) +- [#180](https://github.com/green-code-initiative/ecoCode/pull/180) correction of SonarQube review for MarketPlace (sonar plugin) ### Deleted @@ -47,8 +37,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- [#171](https://github.com/green-code-initiative/ecoCode/issues/171) Add migration mechanism to support "issue - re-keying" +- [#171](https://github.com/green-code-initiative/ecoCode/issues/171) Add migration mechanism to support "issue re-keying" ### Changed @@ -63,10 +52,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- [#63](https://github.com/green-code-initiative/ecoCode/issues/63) Update plugins to be compliant for SonarQube - MarketPlace integration ( PR [#79](https://github.com/green-code-initiative/ecoCode/pull/79) ) -- [#88](https://github.com/green-code-initiative/ecoCode/pull/88) upgrade rules matrix with new ids + refactoring rules - documentation (`RULES.md`) +- [#63](https://github.com/green-code-initiative/ecoCode/issues/63) Update plugins to be compliant for SonarQube MarketPlace integration ( PR [#79](https://github.com/green-code-initiative/ecoCode/pull/79) ) +- [#88](https://github.com/green-code-initiative/ecoCode/pull/88) upgrade rules matrix with new ids + refactoring rules documentation (`RULES.md`) ### Deleted @@ -82,20 +69,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- [#40](https://github.com/green-code-initiative/ecoCode/issues/40) Refactoring of package names (`cnumr` - to `greencodeinitiative`) +- [#40](https://github.com/green-code-initiative/ecoCode/issues/40) Refactoring of package names (`cnumr` to `greencodeinitiative`) - [#58](https://github.com/green-code-initiative/ecoCode/issues/58) check and upgrade compatibility to SonarQube 9.9 - move common init scripts to `ecoCode-common` repository -- modifying documentation and move `CONTRIBUTING.md`, `CODE_STYLE.md` and `INSTALL.md` to common doc in `ecoCode-common` - repository -- security / performance optimizations : correction of `sonarcloud.io` security hotspots (java / php, python) and move - Pattern compilation to static attribute -- [#65](https://github.com/green-code-initiative/ecoCode/issues/65) Create a test project to check new plugin rule in - real environment -- [#71](https://github.com/green-code-initiative/ecoCode/issues/71) After an PHP analysis, no ecocode code smells - appears in my Sonar project -- [#64](https://github.com/green-code-initiative/ecoCode/issues/64) Python: ecoCode plugin with SonarQube, no code-smell - detection +- modifying documentation and move `CONTRIBUTING.md`, `CODE_STYLE.md` and `INSTALL.md` to common doc in `ecoCode-common` repository +- security / performance optimizations : correction of `sonarcloud.io` security hotspots (java / php, python) and move Pattern compilation to static attribute +- [#65](https://github.com/green-code-initiative/ecoCode/issues/65) Create a test project to check new plugin rule in real environment +- [#71](https://github.com/green-code-initiative/ecoCode/issues/71) After an PHP analysis, no ecocode code smells appears in my Sonar project +- [#64](https://github.com/green-code-initiative/ecoCode/issues/64) Python: ecoCode plugin with SonarQube, no code-smell detection - [#55](https://github.com/green-code-initiative/ecoCode/issues/55) rename `eco-conception` tag of rules to `eco-design` - [#76](https://github.com/green-code-initiative/ecoCode/issues/76) correction of SonarQube plugins homepage link broken - documentation upgrade @@ -109,18 +90,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - [#23](https://github.com/green-code-initiative/ecoCode/pull/23) Add images to the description files. -- [#46](https://github.com/green-code-initiative/ecoCode/pull/46) Add CONTRIBUTING.MD, CODE_OF_CONDUCT.md and - CODE_STYLE.md +- [#46](https://github.com/green-code-initiative/ecoCode/pull/46) Add CONTRIBUTING.MD, CODE_OF_CONDUCT.md and CODE_STYLE.md ### Changed -- [#27](https://github.com/green-code-initiative/ecoCode/pull/27) Fix [WARNING] Maven-shade-plugin overlapping classes - and upgrade SonarRuntime. +- [#27](https://github.com/green-code-initiative/ecoCode/pull/27) Fix [WARNING] Maven-shade-plugin overlapping classes and upgrade SonarRuntime. - [#33](https://github.com/green-code-initiative/ecoCode/issues/33) Update plugin description in code -- [#42](https://github.com/green-code-initiative/ecoCode/issues/42) Fix Crash SonarQube analysis because of some - ClassCast Exceptions -- [#48](https://github.com/green-code-initiative/ecoCode/pull/48) correction SONAR issue info - delete public keyword on - tests +- [#42](https://github.com/green-code-initiative/ecoCode/issues/42) Fix Crash SonarQube analysis because of some ClassCast Exceptions +- [#48](https://github.com/green-code-initiative/ecoCode/pull/48) correction SONAR issue info - delete public keyword on tests - Improve "build" GitHub actions to execute checks on branches from fork repositories ## [0.2.1] - 2022-12-30 @@ -177,4 +154,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [0.1.1]: https://github.com/green-code-initiative/ecoCode/compare/v0.1.0...v0.1.1 -[0.1.0]: https://github.com/green-code-initiative/ecoCode/releases/tag/v0.1.0 +[0.1.0]: https://github.com/green-code-initiative/ecoCode/releases/tag/v0.1.0 \ No newline at end of file From a5b2cbb39d59e2d2f26c6036648f5c807a48c64e Mon Sep 17 00:00:00 2001 From: utarwyn Date: Mon, 5 Jun 2023 21:51:30 +0200 Subject: [PATCH 084/170] Update RULES.md --- RULES.md | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/RULES.md b/RULES.md index 5d664f2ee..49d42e38f 100644 --- a/RULES.md +++ b/RULES.md @@ -9,20 +9,20 @@ Some are applicable for different technologies. - 🚀 Rule to implement - 🚫 Non applicable rule -| Rule key | Name | Description | Reference/Validation | Java | Php | JS | Python | Rust | -|--|--|--|--|--|--|--|--|--| -| | Use official social media sharing buttons | These JavaScript plugins are very resource-intensive: to work, they require a large number of requests and download heavy files. It is better to prefer direct links. | [cnumr best practices (3rd edition) BP_019](https://github.com/cnumr/best-practices/blob/main/chapters/BP_019_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | -| | Non-grouped similar CSS declarations | When multiple Document Object Model (DOM) elements have common CSS properties, declare them together in the same style sheet. This method reduces the weight of CSS. |[cnumr best practices (3rd edition) BP_025](https://github.com/cnumr/best-practices/blob/main/chapters/BP_025_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | -| | CSS shorthand notations not used | Reduces the weight of the style sheet. | [cnumr best practices (3rd edition) BP_026](https://github.com/cnumr/best-practices/blob/main/chapters/BP_026_fr.md) | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | -| | CSS print not included | This style sheet reduces the number of pages printed. | [cnumr best practices (3rd edition) BP_027](https://github.com/cnumr/best-practices/blob/main/chapters/BP_027_fr.md) | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | -| | Non-standard fonts used | Prefer standard fonts, as they are already present on the user's computer, so they do not need to download them. This saves bandwidth, while speeding up the display of the site. | [cnumr best practices (3rd edition) BP_029](https://github.com/cnumr/best-practices/blob/main/chapters/BP_029_fr.md) | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | -| | Non-outsourced CSS and Javascript | If you include CSS or JavaScript code in the body of the HTML file, while the HTML file is used by several pages (or even the entire site), this code must be transferred for each page requested by the user, which increases the volume of data transmitted. | [cnumr best practices (3rd edition) BP_032](https://github.com/cnumr/best-practices/blob/main/chapters/BP_032_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | -| | Resize images browser-side | Do not resize images using the HEIGHT and WIDTH attributes of the HTML code. This approach requires transferring these images to their original size, wasting bandwidth and CPU cycles. | [cnumr best practices (3rd edition) BP_034](https://github.com/cnumr/best-practices/blob/main/chapters/BP_034_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | +| Rule key | Name | Description | Reference/Validation | Java | Php | JS | Python | Rust | +|-|--|--|--|--|--|--|--|--| +| | Use official social media sharing buttons | These JavaScript plugins are very resource-intensive: to work, they require a large number of requests and download heavy files. It is better to prefer direct links. | [cnumr best practices (3rd edition) BP_019](https://github.com/cnumr/best-practices/blob/main/chapters/BP_019_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | +| | Non-grouped similar CSS declarations | When multiple Document Object Model (DOM) elements have common CSS properties, declare them together in the same style sheet. This method reduces the weight of CSS. |[cnumr best practices (3rd edition) BP_025](https://github.com/cnumr/best-practices/blob/main/chapters/BP_025_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | +| | CSS shorthand notations not used | Reduces the weight of the style sheet. | [cnumr best practices (3rd edition) BP_026](https://github.com/cnumr/best-practices/blob/main/chapters/BP_026_fr.md) | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | +| | CSS print not included | This style sheet reduces the number of pages printed. | [cnumr best practices (3rd edition) BP_027](https://github.com/cnumr/best-practices/blob/main/chapters/BP_027_fr.md) | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | +| | Non-standard fonts used | Prefer standard fonts, as they are already present on the user's computer, so they do not need to download them. This saves bandwidth, while speeding up the display of the site. | [cnumr best practices (3rd edition) BP_029](https://github.com/cnumr/best-practices/blob/main/chapters/BP_029_fr.md) | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | +| | Non-outsourced CSS and Javascript | If you include CSS or JavaScript code in the body of the HTML file, while the HTML file is used by several pages (or even the entire site), this code must be transferred for each page requested by the user, which increases the volume of data transmitted. | [cnumr best practices (3rd edition) BP_032](https://github.com/cnumr/best-practices/blob/main/chapters/BP_032_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | +| | Resize images browser-side | Do not resize images using the HEIGHT and WIDTH attributes of the HTML code. This approach requires transferring these images to their original size, wasting bandwidth and CPU cycles. | [cnumr best practices (3rd edition) BP_034](https://github.com/cnumr/best-practices/blob/main/chapters/BP_034_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | | EC10 | Use unoptimized vector images | Less heavy SVG images using less bandwidth | [cnumr best practices (3rd edition) BP_036](https://github.com/cnumr/best-practices/blob/main/chapters/BP_036_fr.md) | 🚧 | 🚀 | 🚀 | ✅ | 🚀 | -| | Using too many CSS/javascript animations | JavaScript/CSS animations can be very expensive in terms of CPU cycles and memory consumption. | [cnumr best practices (3rd edition) BP_039](https://github.com/cnumr/best-practices/blob/main/chapters/BP_039_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | -| | Modify the DOM when traversing it | Modifying the DOM (Document Object Model) as you traverse it can lead to situations where the loop becomes very resource-intensive, especially CPU cycles. | [cnumr best practices (3rd edition) BP_041](https://github.com/cnumr/best-practices/blob/main/chapters/BP_041_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | -| | Edit DOM elements to make it invisible | When an element of the Document Object Model (DOM) needs to be modified by several properties, each change in style or content will generate a repaint or reflow. | [cnumr best practices (3rd edition) BP_042](https://github.com/cnumr/best-practices/blob/main/chapters/BP_042_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | -| | Modify several CSS properties all at once | To limit the number of repaints/reflows, it is recommended not to modify properties one by one. | [cnumr best practices (3rd edition) BP_045](https://github.com/cnumr/best-practices/blob/main/chapters/BP_045_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | +| | Using too many CSS/javascript animations | JavaScript/CSS animations can be very expensive in terms of CPU cycles and memory consumption. | [cnumr best practices (3rd edition) BP_039](https://github.com/cnumr/best-practices/blob/main/chapters/BP_039_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | +| | Modify the DOM when traversing it | Modifying the DOM (Document Object Model) as you traverse it can lead to situations where the loop becomes very resource-intensive, especially CPU cycles. | [cnumr best practices (3rd edition) BP_041](https://github.com/cnumr/best-practices/blob/main/chapters/BP_041_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | +| | Edit DOM elements to make it invisible | When an element of the Document Object Model (DOM) needs to be modified by several properties, each change in style or content will generate a repaint or reflow. | [cnumr best practices (3rd edition) BP_042](https://github.com/cnumr/best-practices/blob/main/chapters/BP_042_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | +| | Modify several CSS properties all at once | To limit the number of repaints/reflows, it is recommended not to modify properties one by one. (linter key : `@ecocode/no-multiple-style-changes`) | [cnumr best practices (3rd edition) BP_045](https://github.com/cnumr/best-practices/blob/main/chapters/BP_045_fr.md) | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | | EC34 | Using try...catch...finally calls | When an exception is thrown, a variable (the exception itself) is created in the catch block and destroyed at the end of the block. Creating this variable and destroying it consumes CPU cycles and RAM unnecessarily. That is why it is important not to use this construction and to prefer, as much as possible, a logical test. | [cnumr best practices (3rd edition) BP_047 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | ✅ | 🚀 | ✅ | 🚀 | | EC22 | The use of methods for basic operations | Using methods for basic operations consumes additional system resources. The interpreter must in effect and solve the objects and then the methods, just to carry out these simple operations of the language. | [cnumr best practices (3rd edition) BP_048 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | ✅ | 🚀 | 🚀 | 🚀 | | ??? | Call a DOM element multiple times without caching (linter key : `@ecocode/no-multiple-access-dom-element`) | Access to the Document Object Model (DOM) is costly in terms of CPU resources (CPU cycles). Also, when you use the same DOM element from JavaScript multiple times, store its reference in a variable so that you do not go through the DOM again for the same element. | [cnumr best practices (3rd edition) BP_049](https://github.com/cnumr/best-practices/blob/main/chapters/BP_049_fr.md) | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | @@ -49,3 +49,6 @@ Some are applicable for different technologies. | EC27 | Usage of system.arraycopy to copy arrays | Programs spend most of the time in loops. These can be resource consuming, especially when they integrate heavy processing (IO access). Moreover, the size of the data and processing inside the loops will not allow full use of hardware mechanisms such as the cache or compiler optimization mechanisms. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | | EC404 | Avoid list comprehension in iterations | Use generator comprehension instead of list comprehension in for loop declaration | | 🚫 | 🚫 | 🚫 | ✅ | 🚫 | | EC203 | Detect unoptimized file formats | When it is possible, to use svg format image over other image format | | 🚀 | 🚀 | 🚀 | ✅ | 🚀 | +| | Avoid high accuracy geolocation | Avoid using high accuracy geolocation in web applications (linter key : `@ecocode/avoid-high-accuracy-geolocation`) | | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | +| | No import all from library | Should not import all from library (linter key : `@ecocode/no-import-all-from-library`) | | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | +| | Prefer collections with pagination | Prefer API collections with pagination (linter key : `@ecocode/prefer-collections-with-pagination`) | | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | From 6f978ee4d7b688090af0398c8029fbb26771a292 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Tue, 6 Jun 2023 09:58:59 +0200 Subject: [PATCH 085/170] update AvoidFullSQLRequest.php test to check the case sensitivity --- .../test/resources/checks/AvoidFullSQLRequest.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php b/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php index 90e9907fb..239f6ab79 100644 --- a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php +++ b/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php @@ -1,8 +1,8 @@ SqlCall($sqlQuery1); OtherClass->SqlCall($sqlQuery2); OtherClass->SqlCall($sqlQuery3); From a0725f1f5a24c5ad2898c87229549e396a15170b Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Tue, 6 Jun 2023 10:48:38 +0200 Subject: [PATCH 086/170] update SQL queries in tests --- .../src/test/resources/checks/AvoidFullSQLRequest.php | 8 ++++---- .../resources/checks/AvoidUsingGlobalVariablesCheck.php | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php b/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php index 239f6ab79..ac8040ee4 100644 --- a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php +++ b/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php @@ -1,6 +1,6 @@ SqlCall('SELECT * FROM'); // NOK {{Don't use the query SELECT * FROM}} - OtherClass->SqlCall('SELECT DISTINCT * FROM'); // NOK {{Don't use the query SELECT * FROM}} - OtherClass->SqlCall('SELECT name FROM'); + OtherClass->SqlCall('SeLeCt DiStInCt * FrOm'); // NOK {{Don't use the query SELECT * FROM}} + OtherClass->SqlCall('select name from'); } public function passeAsVariable() { - $sqlQuery1 = 'SeLeCt * FrOm'; // NOK {{Don't use the query SELECT * FROM}} + $sqlQuery1 = 'SELECT * FROM'; // NOK {{Don't use the query SELECT * FROM}} $sqlQuery2 = 'SeLeCt DiStInCt * FrOm'; // NOK {{Don't use the query SELECT * FROM}} $sqlQuery3 = 'select name from'; OtherClass->SqlCall($sqlQuery1); diff --git a/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php b/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php index e3a1eb4dd..3431ab82e 100644 --- a/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php +++ b/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php @@ -2,6 +2,7 @@ $a = 1; $b = 2; + function somme() // NOK {{Prefer local variables to globals}} { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; From 3dbe0aa1d66f42da22f9e2297a3e6b03564c35cc Mon Sep 17 00:00:00 2001 From: Jean-Baptiste GINGUENE Date: Tue, 6 Jun 2023 10:51:49 +0200 Subject: [PATCH 087/170] CS fix --- .../src/test/resources/checks/AvoidFullSQLRequest.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php b/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php index ac8040ee4..4ef22c15c 100644 --- a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php +++ b/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php @@ -15,9 +15,9 @@ public function literalString() public function passeAsVariable() { - $sqlQuery1 = 'SELECT * FROM'; // NOK {{Don't use the query SELECT * FROM}} - $sqlQuery2 = 'SeLeCt DiStInCt * FrOm'; // NOK {{Don't use the query SELECT * FROM}} - $sqlQuery3 = 'select name from'; + $sqlQuery1 = 'SELECT * FROM'; // NOK {{Don't use the query SELECT * FROM}} + $sqlQuery2 = 'SeLeCt DiStInCt * FrOm'; // NOK {{Don't use the query SELECT * FROM}} + $sqlQuery3 = 'select name from'; OtherClass->SqlCall($sqlQuery1); OtherClass->SqlCall($sqlQuery2); OtherClass->SqlCall($sqlQuery3); From f4f9c00cef6e947627288021c27de6cadf054498 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 6 Jun 2023 21:29:15 +0200 Subject: [PATCH 088/170] upgrade CHANGELOG.md --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 207017de4..cce68e92e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,11 +6,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] -- [#191](https://github.com/green-code-initiative/ecoCode/issues/191) update rule tags for Java, Python, and PHP plugins. ### Added -- [#109](https://github.com/green-code-initiative/ecoCode/issues/109) PHP rule : **Getting the size of the collection in the loop**. For further [RULES.md](./RULES.md) file. +- [#109](https://github.com/green-code-initiative/ecoCode/issues/109) new PHP rule : Getting the size of the collection in the loop. For further [RULES.md](./RULES.md) file +- [#191](https://github.com/green-code-initiative/ecoCode/issues/191) update rule tags for Java, Python, and PHP plugins - [#113](https://github.com/green-code-initiative/ecoCode/issues/113) new PYTHON rule : Use unoptimized vector images - [#127](https://github.com/green-code-initiative/ecoCode/issues/127) Add Python rule EC404: Usage of generator comprehension instead of list comprehension in for loop declaration - [#192](https://github.com/green-code-initiative/ecoCode/pull/192) Add Python rule EC203: Detect unoptimized file formats From efeb98f0790a47c9c82b581bda540975e7f07d56 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Thu, 8 Jun 2023 07:34:16 +0200 Subject: [PATCH 089/170] [ISSUE 187] typo --- javascript-plugin/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml index ebf069c23..547a2a2df 100644 --- a/javascript-plugin/pom.xml +++ b/javascript-plugin/pom.xml @@ -70,7 +70,7 @@ org.apache.maven.plugins maven-shade-plugin From 738d13a0dc053c14290692259353857b8e019b45 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Thu, 8 Jun 2023 07:41:23 +0200 Subject: [PATCH 090/170] [ISSUE 187] refacto CHANGELOG.md + add 107 changelog --- CHANGELOG.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cce68e92e..0312b6f90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,16 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- [#109](https://github.com/green-code-initiative/ecoCode/issues/109) new PHP rule : Getting the size of the collection in the loop. For further [RULES.md](./RULES.md) file +- [#108](https://github.com/green-code-initiative/ecoCode/issues/108) new Python rule EC66 : Use single quote (') instead of quotation mark (") +- [#109](https://github.com/green-code-initiative/ecoCode/issues/109) new PHP rule EC3 : Getting the size of the collection in the loop. For further [RULES.md](./RULES.md) file +- [#113](https://github.com/green-code-initiative/ecoCode/issues/113) new Python rule EC10 : Use unoptimized vector images +- [#127](https://github.com/green-code-initiative/ecoCode/issues/127) new Python rule EC404 : Usage of generator comprehension instead of list comprehension in for loop declaration - [#191](https://github.com/green-code-initiative/ecoCode/issues/191) update rule tags for Java, Python, and PHP plugins -- [#113](https://github.com/green-code-initiative/ecoCode/issues/113) new PYTHON rule : Use unoptimized vector images -- [#127](https://github.com/green-code-initiative/ecoCode/issues/127) Add Python rule EC404: Usage of generator comprehension instead of list comprehension in for loop declaration -- [#192](https://github.com/green-code-initiative/ecoCode/pull/192) Add Python rule EC203: Detect unoptimized file formats -- [#108](https://github.com/green-code-initiative/ecoCode/issues/108) Add Python rule EC66: Use single quote (') instead of quotation mark (") +- [#192](https://github.com/green-code-initiative/ecoCode/pull/192) new Python rule EC203 : Detect unoptimized file formats ### Changed - [#19](https://github.com/green-code-initiative/ecoCode-common/issues/19) process changed for development environment installation : easier to initialize locally environment (check [`INSTALL.md`](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment) file) +- [#107](https://github.com/green-code-initiative/ecoCode/issues/107) upgrade librairies to SonarQube 10.0.0 - [#196](https://github.com/green-code-initiative/ecoCode/issues/196) updating PHP files to make them following the coding standards (PSR-12) ### Deleted @@ -70,14 +71,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - [#40](https://github.com/green-code-initiative/ecoCode/issues/40) Refactoring of package names (`cnumr` to `greencodeinitiative`) +- [#55](https://github.com/green-code-initiative/ecoCode/issues/55) rename `eco-conception` tag of rules to `eco-design` - [#58](https://github.com/green-code-initiative/ecoCode/issues/58) check and upgrade compatibility to SonarQube 9.9 - move common init scripts to `ecoCode-common` repository - modifying documentation and move `CONTRIBUTING.md`, `CODE_STYLE.md` and `INSTALL.md` to common doc in `ecoCode-common` repository - security / performance optimizations : correction of `sonarcloud.io` security hotspots (java / php, python) and move Pattern compilation to static attribute +- [#64](https://github.com/green-code-initiative/ecoCode/issues/64) Python: ecoCode plugin with SonarQube, no code-smell detection - [#65](https://github.com/green-code-initiative/ecoCode/issues/65) Create a test project to check new plugin rule in real environment - [#71](https://github.com/green-code-initiative/ecoCode/issues/71) After an PHP analysis, no ecocode code smells appears in my Sonar project -- [#64](https://github.com/green-code-initiative/ecoCode/issues/64) Python: ecoCode plugin with SonarQube, no code-smell detection -- [#55](https://github.com/green-code-initiative/ecoCode/issues/55) rename `eco-conception` tag of rules to `eco-design` - [#76](https://github.com/green-code-initiative/ecoCode/issues/76) correction of SonarQube plugins homepage link broken - documentation upgrade From 75d1b0ae3513120f059f068030a59eefafda9118 Mon Sep 17 00:00:00 2001 From: utarwyn Date: Thu, 8 Jun 2023 23:17:42 +0200 Subject: [PATCH 091/170] Update CHANGELOG.md --- CHANGELOG.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cce68e92e..2922e33ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,12 +9,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- [#109](https://github.com/green-code-initiative/ecoCode/issues/109) new PHP rule : Getting the size of the collection in the loop. For further [RULES.md](./RULES.md) file -- [#191](https://github.com/green-code-initiative/ecoCode/issues/191) update rule tags for Java, Python, and PHP plugins -- [#113](https://github.com/green-code-initiative/ecoCode/issues/113) new PYTHON rule : Use unoptimized vector images +- [#109](https://github.com/green-code-initiative/ecoCode/issues/109) Add PHP rule EC3: Getting the size of the collection in the loop. +- [#190](https://github.com/green-code-initiative/ecoCode/pull/190) Add Python rule: Use unoptimized vector images - [#127](https://github.com/green-code-initiative/ecoCode/issues/127) Add Python rule EC404: Usage of generator comprehension instead of list comprehension in for loop declaration - [#192](https://github.com/green-code-initiative/ecoCode/pull/192) Add Python rule EC203: Detect unoptimized file formats - [#108](https://github.com/green-code-initiative/ecoCode/issues/108) Add Python rule EC66: Use single quote (') instead of quotation mark (") +- [#191](https://github.com/green-code-initiative/ecoCode/issues/191) Update rule tags for Java, Python, and PHP plugins +- Add JavaScript rules from [ecoCode ESLint plugin v0.2.0](https://github.com/green-code-initiative/ecoCode-linter/releases/tag/eslint-plugin%2F0.2.0) ### Changed @@ -154,4 +155,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [0.1.1]: https://github.com/green-code-initiative/ecoCode/compare/v0.1.0...v0.1.1 -[0.1.0]: https://github.com/green-code-initiative/ecoCode/releases/tag/v0.1.0 \ No newline at end of file +[0.1.0]: https://github.com/green-code-initiative/ecoCode/releases/tag/v0.1.0 From caaef82d86c3456a66cfd848f266b57ee05cdf67 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Mon, 12 Jun 2023 23:03:12 +0200 Subject: [PATCH 092/170] merge main - conflict --- CHANGELOG.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0312b6f90..e1dbda695 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,8 +13,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#109](https://github.com/green-code-initiative/ecoCode/issues/109) new PHP rule EC3 : Getting the size of the collection in the loop. For further [RULES.md](./RULES.md) file - [#113](https://github.com/green-code-initiative/ecoCode/issues/113) new Python rule EC10 : Use unoptimized vector images - [#127](https://github.com/green-code-initiative/ecoCode/issues/127) new Python rule EC404 : Usage of generator comprehension instead of list comprehension in for loop declaration -- [#191](https://github.com/green-code-initiative/ecoCode/issues/191) update rule tags for Java, Python, and PHP plugins +- [#190](https://github.com/green-code-initiative/ecoCode/pull/190) Add Python rule: Use unoptimized vector images +- [#191](https://github.com/green-code-initiative/ecoCode/issues/191) Update rule tags for Java, Python, and PHP plugins - [#192](https://github.com/green-code-initiative/ecoCode/pull/192) new Python rule EC203 : Detect unoptimized file formats +- Add JavaScript rules from [ecoCode ESLint plugin v0.2.0](https://github.com/green-code-initiative/ecoCode-linter/releases/tag/eslint-plugin%2F0.2.0) ### Changed @@ -155,4 +157,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [0.1.1]: https://github.com/green-code-initiative/ecoCode/compare/v0.1.0...v0.1.1 -[0.1.0]: https://github.com/green-code-initiative/ecoCode/releases/tag/v0.1.0 \ No newline at end of file +[0.1.0]: https://github.com/green-code-initiative/ecoCode/releases/tag/v0.1.0 From 618cc4b29c403ef045f90dce6faa930c97134204 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Mon, 19 Jun 2023 14:44:26 +0200 Subject: [PATCH 093/170] upgrade of maven plugins --- pom.xml | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/pom.xml b/pom.xml index 4f15d9b78..0df08ecd4 100644 --- a/pom.xml +++ b/pom.xml @@ -55,9 +55,6 @@ green-code-initiative https://sonarcloud.io - - 0.8.8 - 7.15.0.30507 3.19.0.10254 3.25.0.9077 @@ -67,7 +64,7 @@ 2.1.0.1111 1.21.0.505 true - 3.4.1 + 5.9.1 3.23.1 @@ -179,12 +176,12 @@ org.apache.maven.plugins maven-compiler-plugin - 3.10.1 + 3.11.0 org.apache.maven.plugins maven-dependency-plugin - 3.3.0 + 3.6.0 org.sonarsource.sonar-packaging-maven-plugin @@ -194,12 +191,17 @@ org.apache.maven.plugins maven-shade-plugin - ${maven-shade-plugin.version} + 3.5.0 + + + org.apache.maven.plugins + maven-surefire-plugin + 3.1.2 org.jacoco jacoco-maven-plugin - ${jacoco.version} + 0.8.10 From 8f5351d47fcb053226753e8307173704af69c3d5 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Mon, 19 Jun 2023 14:48:42 +0200 Subject: [PATCH 094/170] upgrade of maven plugins - update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2922e33ec..ebddaff2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#19](https://github.com/green-code-initiative/ecoCode-common/issues/19) process changed for development environment installation : easier to initialize locally environment (check [`INSTALL.md`](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment) file) - [#196](https://github.com/green-code-initiative/ecoCode/issues/196) updating PHP files to make them following the coding standards (PSR-12) +- technical : upgrade of maven plugins versions ### Deleted From 1a3661bf47993655c3065bf41b15614e30737973 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Mon, 19 Jun 2023 18:29:56 +0200 Subject: [PATCH 095/170] conflit main - correction --- pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index c284047bc..7b861bf27 100644 --- a/pom.xml +++ b/pom.xml @@ -199,11 +199,6 @@ package - - - org.apache.maven.plugins - maven-surefire-plugin - 3.1.2 shade @@ -239,6 +234,11 @@ + + org.apache.maven.plugins + maven-surefire-plugin + 3.1.2 + org.jacoco jacoco-maven-plugin From f710e6f666a20c4ea8d20a4196b32e0dcdb2cec5 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Thu, 22 Jun 2023 21:40:34 +0200 Subject: [PATCH 096/170] [ISSUE 187] clean useless property --- pom.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/pom.xml b/pom.xml index 7b861bf27..da289faa3 100644 --- a/pom.xml +++ b/pom.xml @@ -65,8 +65,6 @@ 1.21.0.505 true - - 0.8.10 5.9.1 3.23.1 From 3af964a7ae55b3e3339f090381bdd952c4fc139c Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 23 Jun 2023 23:08:00 +0200 Subject: [PATCH 097/170] correction CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80c2abeee..3f1c1e90f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - [#19](https://github.com/green-code-initiative/ecoCode-common/issues/19) process changed for development environment installation : easier to initialize locally environment (check [`INSTALL.md`](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment) file) -- [#107](https://github.com/green-code-initiative/ecoCode/issues/107) upgrade librairies to SonarQube 10.0.0 +- [#187](https://github.com/green-code-initiative/ecoCode/issues/187) upgrade librairies to SonarQube 10.0.0 - [#196](https://github.com/green-code-initiative/ecoCode/issues/196) updating PHP files to make them following the coding standards (PSR-12) - technical : upgrade of maven plugins versions From 39e7044b70aa71339bb205b288b246e96740246a Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 23 Jun 2023 23:27:20 +0200 Subject: [PATCH 098/170] [ISSUE 194] add automatic stale tag on stale PRs --- .github/workflows/stale_tag.yml | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 .github/workflows/stale_tag.yml diff --git a/.github/workflows/stale_tag.yml b/.github/workflows/stale_tag.yml new file mode 100644 index 000000000..4c7a9ff96 --- /dev/null +++ b/.github/workflows/stale_tag.yml @@ -0,0 +1,21 @@ +name: "Label stale PRs" +on: + schedule: + - cron: "30 1 * * *" + workflow_dispatch: + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v8.0.0 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + days-before-issue-stale: -1 # We don't want to address issues + days-before-pr-stale: 30 + days-before-issue-close: -1 # We don't want to close issues in this action + days-before-pr-close: -1 # We don't want to close PR in this action + stale-pr-label: stale + stale-pr-message: | + This PR has been automatically marked as stale because it has no activity for 30 days. + Please add a comment if you want to keep the issue open. Thank you for your contributions! \ No newline at end of file From 20e2e90ccca44306b3656d363d74b648bec1c720 Mon Sep 17 00:00:00 2001 From: utarwyn Date: Wed, 7 Jun 2023 20:18:31 +0200 Subject: [PATCH 099/170] Cleanup plugins and dependencies --- java-plugin/pom.xml | 17 ++++------ .../java/JavaRulesDefinition.java | 20 +++++------ .../UnnecessarilyAssignValuesToVariables.java | 33 +++--------------- .../java/JavaPluginTest.java | 34 +++---------------- .../java/JavaRulesDefinitionTest.java | 10 ++++-- javascript-plugin/pom.xml | 11 +++--- .../javascript/JavaScriptPluginTest.java | 31 +++-------------- php-plugin/pom.xml | 12 ++++--- .../php/PhpPluginTest.java | 15 ++++---- pom.xml | 15 ++++---- python-plugin/pom.xml | 10 +++--- .../python/PythonPluginTest.java | 15 ++++---- 12 files changed, 80 insertions(+), 143 deletions(-) diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index 773c3a0bd..c750fd98e 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -28,22 +28,11 @@ sonar-plugin-api - - org.sonarsource.sonarqube - sonar-plugin-api-impl - - org.sonarsource.analyzer-commons sonar-analyzer-commons - - org.apache.commons - commons-lang3 - 3.11 - - com.google.re2j @@ -69,6 +58,12 @@ test + + org.mockito + mockito-junit-jupiter + test + + diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java index 37a82c438..09a89e58b 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java @@ -19,19 +19,15 @@ */ package fr.greencodeinitiative.java; +import org.sonar.api.SonarRuntime; +import org.sonar.api.server.rule.RulesDefinition; +import org.sonarsource.analyzer.commons.RuleMetadataLoader; + import java.util.ArrayList; import java.util.Collections; import java.util.Objects; import java.util.Set; -import org.sonar.api.SonarEdition; -import org.sonar.api.SonarQubeSide; -import org.sonar.api.SonarRuntime; -import org.sonar.api.internal.SonarRuntimeImpl; -import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.api.utils.Version; -import org.sonarsource.analyzer.commons.RuleMetadataLoader; - /** * Declare rule metadata in server repository of rules. * That allows to list the rules in the page "Rules". @@ -48,12 +44,16 @@ public class JavaRulesDefinition implements RulesDefinition { public static final String LANGUAGE = "java"; public static final String REPOSITORY_KEY = "ecocode-java"; + private final SonarRuntime sonarRuntime; + + public JavaRulesDefinition(SonarRuntime sonarRuntime) { + this.sonarRuntime = sonarRuntime; + } + @Override public void define(Context context) { NewRepository repository = context.createRepository(REPOSITORY_KEY, LANGUAGE).setName(NAME); - SonarRuntime sonarRuntime = SonarRuntimeImpl.forSonarQube(Version.create(10, 0), SonarQubeSide.SCANNER, SonarEdition.DEVELOPER); - RuleMetadataLoader ruleMetadataLoader = new RuleMetadataLoader(RESOURCE_BASE_PATH, sonarRuntime); ruleMetadataLoader.addRulesByAnnotatedClass(repository, new ArrayList<>(RulesList.getChecks())); diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java index 0e334905d..d8a7e69da 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java @@ -1,39 +1,16 @@ package fr.greencodeinitiative.java.checks; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.CheckForNull; - -import org.apache.commons.lang3.StringUtils; import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.JavaFileScanner; import org.sonar.plugins.java.api.JavaFileScannerContext; -import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; -import org.sonar.plugins.java.api.tree.BaseTreeVisitor; -import org.sonar.plugins.java.api.tree.BinaryExpressionTree; -import org.sonar.plugins.java.api.tree.BlockTree; -import org.sonar.plugins.java.api.tree.ExpressionTree; -import org.sonar.plugins.java.api.tree.ForEachStatement; -import org.sonar.plugins.java.api.tree.IdentifierTree; -import org.sonar.plugins.java.api.tree.IfStatementTree; -import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; -import org.sonar.plugins.java.api.tree.MethodInvocationTree; -import org.sonar.plugins.java.api.tree.NewClassTree; -import org.sonar.plugins.java.api.tree.ReturnStatementTree; -import org.sonar.plugins.java.api.tree.StatementTree; -import org.sonar.plugins.java.api.tree.ThrowStatementTree; -import org.sonar.plugins.java.api.tree.Tree; +import org.sonar.plugins.java.api.tree.*; import org.sonar.plugins.java.api.tree.Tree.Kind; -import org.sonar.plugins.java.api.tree.TypeCastTree; -import org.sonar.plugins.java.api.tree.UnaryExpressionTree; -import org.sonar.plugins.java.api.tree.VariableTree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; +import javax.annotation.CheckForNull; +import java.util.*; + @Rule(key = "EC63", name = "Developpement", description = "Do not unnecessarily assign values to variables", priority = Priority.MINOR, tags = {"eco-design", "ecocode", "memory"}) @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S63") @@ -191,7 +168,7 @@ private void checkImmediatelyReturnedVariable(BlockTree tree) { String lastStatementIdentifier = getReturnOrThrowIdentifier(lastStatement); if (lastStatementIdentifier != null) { String identifier = variableTree.simpleName().name(); - if (StringUtils.equals(lastStatementIdentifier, identifier)) { + if (lastStatementIdentifier.equals(identifier)) { context.reportIssue(this, variableTree.initializer(), errorMessage); } } diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java index 649268421..8b7295d07 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java @@ -19,47 +19,23 @@ */ package fr.greencodeinitiative.java; -import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.sonar.api.Plugin; -import org.sonar.api.SonarEdition; -import org.sonar.api.SonarProduct; -import org.sonar.api.SonarQubeSide; import org.sonar.api.SonarRuntime; -import org.sonar.api.utils.Version; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; class JavaPluginTest { @Test void testName() { - Plugin.Context context = new Plugin.Context(new MockedSonarRuntime()); + SonarRuntime sonarRuntime = mock(SonarRuntime.class); + Plugin.Context context = new Plugin.Context(sonarRuntime); new JavaPlugin().define(context); assertThat(context.getExtensions()).hasSize(2); } - private static class MockedSonarRuntime implements SonarRuntime { - - @Override - public Version getApiVersion() { - return Version.create(10, 0); - } - - @Override - public SonarProduct getProduct() { - return SonarProduct.SONARQUBE; - } - - @Override - public SonarQubeSide getSonarQubeSide() { - return SonarQubeSide.SCANNER; - } - - @Override - public SonarEdition getEdition() { - return SonarEdition.COMMUNITY; - } - } - } diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java index 45bd537e2..aa5d5c9a1 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java @@ -23,14 +23,18 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.sonar.api.SonarRuntime; import org.sonar.api.rules.RuleType; import org.sonar.api.server.debt.DebtRemediationFunction.Type; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.api.server.rule.RulesDefinition.Param; import org.sonar.api.server.rule.RulesDefinition.Repository; import org.sonar.api.server.rule.RulesDefinition.Rule; +import org.sonar.api.utils.Version; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; class JavaRulesDefinitionTest { @@ -38,8 +42,10 @@ class JavaRulesDefinitionTest { @BeforeEach void init() { - final JavaRulesDefinition rulesDefinition = new JavaRulesDefinition(); - final RulesDefinition.Context context = new RulesDefinition.Context(); + SonarRuntime sonarRuntime = mock(SonarRuntime.class); + doReturn(Version.create(0, 0)).when(sonarRuntime).getApiVersion(); + JavaRulesDefinition rulesDefinition = new JavaRulesDefinition(sonarRuntime); + RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); repository = context.repository(JavaRulesDefinition.REPOSITORY_KEY); } diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml index 547a2a2df..ab0c3a81c 100644 --- a/javascript-plugin/pom.xml +++ b/javascript-plugin/pom.xml @@ -28,11 +28,6 @@ sonar-plugin-api - - org.sonarsource.sonarqube - sonar-plugin-api-impl - - org.sonarsource.analyzer-commons sonar-analyzer-commons @@ -50,6 +45,12 @@ test + + org.mockito + mockito-junit-jupiter + test + + diff --git a/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java b/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java index 3f8ed8f3f..84534777c 100644 --- a/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java +++ b/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java @@ -1,41 +1,20 @@ package fr.greencodeinitiative.javascript; import org.junit.jupiter.api.Test; -import org.sonar.api.*; -import org.sonar.api.utils.Version; +import org.sonar.api.Plugin; +import org.sonar.api.SonarRuntime; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; class JavaScriptPluginTest { @Test void extensions() { - Plugin.Context context = new Plugin.Context(new MockedSonarRuntime()); + SonarRuntime sonarRuntime = mock(SonarRuntime.class); + Plugin.Context context = new Plugin.Context(sonarRuntime); new JavaScriptPlugin().define(context); assertThat(context.getExtensions()).hasSize(1); } - private static class MockedSonarRuntime implements SonarRuntime { - - @Override - public Version getApiVersion() { - return Version.create(10, 0); - } - - @Override - public SonarProduct getProduct() { - return SonarProduct.SONARQUBE; - } - - @Override - public SonarQubeSide getSonarQubeSide() { - return SonarQubeSide.SCANNER; - } - - @Override - public SonarEdition getEdition() { - return SonarEdition.COMMUNITY; - } - } - } diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index 3ee2639c8..ad70f265d 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -28,11 +28,6 @@ sonar-plugin-api - - org.sonarsource.sonarqube - sonar-plugin-api-impl - - @@ -45,6 +40,13 @@ assertj-core test + + + org.mockito + mockito-junit-jupiter + test + + diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java index b64679cbb..9f256645a 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java @@ -19,22 +19,21 @@ */ package fr.greencodeinitiative.php; -import static org.assertj.core.api.Assertions.assertThat; 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; +import static org.mockito.Mockito.mock; public class PhpPluginTest { + @Test public void test() { - SonarRuntime sonarRuntime = SonarRuntimeImpl.forSonarQube(Version.create(10, 0), SonarQubeSide.SCANNER, SonarEdition.DEVELOPER); - Plugin.Context context = new PluginContextImpl.Builder().setSonarRuntime(sonarRuntime).build(); + SonarRuntime sonarRuntime = mock(SonarRuntime.class); + Plugin.Context context = new Plugin.Context(sonarRuntime); new PHPPlugin().define(context); assertThat(context.getExtensions()).hasSize(1); } + } diff --git a/pom.xml b/pom.xml index da289faa3..bead6defc 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,6 @@ https://sonarcloud.io 9.4.0.54424 - 10.0.0.68432 7.19.0.31550 4.3.0.11660 3.29.0.9684 @@ -67,6 +66,7 @@ 5.9.1 3.23.1 + 5.3.1 1.7 @@ -89,12 +89,6 @@ ${sonar-analyzer-commons.version} - - org.sonarsource.sonarqube - sonar-plugin-api-impl - ${sonar-plugin-api-impl.version} - - com.google.re2j @@ -160,6 +154,13 @@ test + + org.mockito + mockito-junit-jupiter + ${mockito.version} + test + + org.sonarsource.python python-checks-testkit diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index e16bdca63..7fd808178 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -27,10 +27,6 @@ org.sonarsource.sonarqube sonar-plugin-api - - org.sonarsource.sonarqube - sonar-plugin-api-impl - @@ -44,6 +40,12 @@ test + + org.mockito + mockito-junit-jupiter + test + + diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java index a5ad52390..2d22fcbbf 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java @@ -19,22 +19,21 @@ */ package fr.greencodeinitiative.python; -import static org.assertj.core.api.Assertions.assertThat; 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; +import static org.mockito.Mockito.mock; public class PythonPluginTest { + @Test public void test() { - SonarRuntime sonarRuntime = SonarRuntimeImpl.forSonarQube(Version.create(10, 0), SonarQubeSide.SCANNER, SonarEdition.DEVELOPER); - Plugin.Context context = new PluginContextImpl.Builder().setSonarRuntime(sonarRuntime).build(); + SonarRuntime sonarRuntime = mock(SonarRuntime.class); + Plugin.Context context = new Plugin.Context(sonarRuntime); new PythonPlugin().define(context); assertThat(context.getExtensions()).hasSize(1); } + } From 4b13735e88f06b7aa39ae671dba2d675b3e3b5be Mon Sep 17 00:00:00 2001 From: utarwyn Date: Wed, 7 Jun 2023 20:43:51 +0200 Subject: [PATCH 100/170] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f1c1e90f..75f628259 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#19](https://github.com/green-code-initiative/ecoCode-common/issues/19) process changed for development environment installation : easier to initialize locally environment (check [`INSTALL.md`](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md#howto-install-sonarqube-dev-environment) file) - [#187](https://github.com/green-code-initiative/ecoCode/issues/187) upgrade librairies to SonarQube 10.0.0 - [#196](https://github.com/green-code-initiative/ecoCode/issues/196) updating PHP files to make them following the coding standards (PSR-12) +- [#201](https://github.com/green-code-initiative/ecoCode/pull/201) Clean-up plugins and dependencies - technical : upgrade of maven plugins versions ### Deleted @@ -159,3 +160,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [0.1.1]: https://github.com/green-code-initiative/ecoCode/compare/v0.1.0...v0.1.1 [0.1.0]: https://github.com/green-code-initiative/ecoCode/releases/tag/v0.1.0 + From 53087537b391da13ead5fa99c12867b8349f80dd Mon Sep 17 00:00:00 2001 From: utarwyn Date: Fri, 9 Jun 2023 00:01:55 +0200 Subject: [PATCH 101/170] Update license in file headers --- .../java/JavaCheckRegistrar.java | 9 +++---- .../greencodeinitiative/java/JavaPlugin.java | 12 +++------ .../java/JavaRulesDefinition.java | 9 +++---- .../greencodeinitiative/java/RulesList.java | 9 +++---- .../java/checks/package-info.java | 20 -------------- .../java/package-info.java | 20 -------------- .../java/utils/PrinterVisitor.java | 9 +++---- .../java/utils/StringUtils.java | 9 +++---- .../java/utils/package-info.java | 20 -------------- .../java/JavaCheckRegistrarTest.java | 13 +++++----- .../java/JavaPluginTest.java | 9 +++---- .../java/JavaRulesDefinitionTest.java | 9 +++---- .../java/utils/FilesUtils.java | 9 +++---- .../java/utils/StringUtilsTest.java | 9 +++---- .../javascript/JavaScriptPlugin.java | 16 ++++++++++++ .../javascript/JavaScriptRulesDefinition.java | 16 ++++++++++++ .../fr/greencodeinitiative/php/PHPPlugin.java | 13 +++------- .../php/PhpRuleRepository.java | 9 +++---- .../php/checks/IncrementCheck.java | 19 -------------- .../php/PhpPluginTest.java | 9 +++---- .../php/PhpRuleRepositoryTest.java | 9 +++---- .../AvoidUsingGlobalVariablesCheckTest.java | 26 ++----------------- .../php/checks/IncrementCheckTest.java | 22 ---------------- .../python/PythonPlugin.java | 9 +++---- .../python/PythonRuleRepository.java | 23 +++++++--------- .../python/checks/package-info.java | 24 ----------------- .../python/package-info.java | 9 +++---- .../python/PythonPluginTest.java | 9 +++---- .../python/PythonRuleRepositoryTest.java | 9 +++---- 29 files changed, 104 insertions(+), 284 deletions(-) delete mode 100644 java-plugin/src/main/java/fr/greencodeinitiative/java/checks/package-info.java delete mode 100644 java-plugin/src/main/java/fr/greencodeinitiative/java/package-info.java delete mode 100644 java-plugin/src/main/java/fr/greencodeinitiative/java/utils/package-info.java delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/package-info.java diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java index 1d92303b1..5705e6ec5 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java @@ -1,7 +1,5 @@ /* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.java; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaPlugin.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaPlugin.java index 1e40808d8..3ccc016e8 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaPlugin.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaPlugin.java @@ -1,7 +1,5 @@ /* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,17 +11,13 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.java; import org.sonar.api.Plugin; -/** - * Entry point of your plugin containing your custom rules - */ public class JavaPlugin implements Plugin { @Override diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java index 09a89e58b..56324e89e 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java @@ -1,7 +1,5 @@ /* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.java; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java index 8f2a47c47..850e141c7 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java @@ -1,7 +1,5 @@ /* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.java; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/package-info.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/package-info.java deleted file mode 100644 index 03dc1c94a..000000000 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package fr.greencodeinitiative.java.checks; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/package-info.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/package-info.java deleted file mode 100644 index 5f3b0c8b2..000000000 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package fr.greencodeinitiative.java; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/PrinterVisitor.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/PrinterVisitor.java index 2cb531718..7e796b1a3 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/PrinterVisitor.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/PrinterVisitor.java @@ -1,7 +1,5 @@ /* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.java.utils; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/StringUtils.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/StringUtils.java index 78f6e4df6..bc6ec9d89 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/StringUtils.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/StringUtils.java @@ -1,7 +1,5 @@ /* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.java.utils; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/package-info.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/package-info.java deleted file mode 100644 index f88cc6249..000000000 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package fr.greencodeinitiative.java.utils; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaCheckRegistrarTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaCheckRegistrarTest.java index 3225b1a56..29cc52ae2 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaCheckRegistrarTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaCheckRegistrarTest.java @@ -1,7 +1,5 @@ /* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,16 +11,16 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.java; -import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.sonar.plugins.java.api.CheckRegistrar; +import static org.assertj.core.api.Assertions.assertThat; + class JavaCheckRegistrarTest { @Test @@ -35,4 +33,5 @@ void checkNumberRules() { assertThat(context.checkClasses()).hasSize(19); assertThat(context.testCheckClasses()).isEmpty(); } + } diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java index 8b7295d07..c925ece4e 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java @@ -1,7 +1,5 @@ /* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.java; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java index aa5d5c9a1..20aabc21c 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java @@ -1,7 +1,5 @@ /* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.java; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/FilesUtils.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/FilesUtils.java index 37be25da4..121607764 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/FilesUtils.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/FilesUtils.java @@ -1,7 +1,5 @@ /* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.java.utils; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/StringUtilsTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/StringUtilsTest.java index c0eee7c3c..25b5b6791 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/StringUtilsTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/StringUtilsTest.java @@ -1,7 +1,5 @@ /* - * SonarQube Java - * Copyright (C) 2012-2021 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.java.utils; diff --git a/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptPlugin.java b/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptPlugin.java index 6959ea2e1..66dba696c 100644 --- a/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptPlugin.java +++ b/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptPlugin.java @@ -1,3 +1,19 @@ +/* + * Copyright (C) 2023 Green Code Initiative + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.javascript; import org.sonar.api.Plugin; diff --git a/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinition.java b/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinition.java index e5fbae09d..f13409ce4 100644 --- a/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinition.java +++ b/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinition.java @@ -1,3 +1,19 @@ +/* + * Copyright (C) 2023 Green Code Initiative + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.javascript; import org.sonar.api.server.rule.RulesDefinition; diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/PHPPlugin.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/PHPPlugin.java index c9bd1ce55..1a7afec6e 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/PHPPlugin.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/PHPPlugin.java @@ -1,7 +1,5 @@ /* - * SonarQube PHP Custom Rules Example - * Copyright (C) 2016-2016 SonarSource SA - * mailto:contact AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,21 +11,18 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.php; import org.sonar.api.Plugin; -/** - * Extension point to define a Sonar Plugin. - */ public class PHPPlugin implements Plugin { @Override public void define(Context context) { context.addExtension(PhpRuleRepository.class); } + } diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java index 89d05f894..d0fd50e53 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java @@ -1,7 +1,5 @@ /* - * SonarQube Python Plugin - * Copyright (C) 2012-2019 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.php; diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java index 1c6168ca3..79bd2cb4a 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java @@ -1,22 +1,3 @@ -/* - * SonarQube PHP Custom Rules Example - * Copyright (C) 2016-2016 SonarSource SA - * mailto:contact AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ package fr.greencodeinitiative.php.checks; import java.util.Collections; diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java index 9f256645a..33736bc4c 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java @@ -1,7 +1,5 @@ /* - * SonarQube Python Plugin - * Copyright (C) 2012-2019 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.php; diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java index 3a124f382..70ef4cae8 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java @@ -1,7 +1,5 @@ /* - * SonarQube Python Plugin - * Copyright (C) 2012-2019 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.php; diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheckTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheckTest.java index 4b8bda378..ca0256117 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheckTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheckTest.java @@ -1,33 +1,11 @@ -/* - * SonarQube PHP Custom Rules Example - * Copyright (C) 2016-2016 SonarSource SA - * mailto:contact AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ package fr.greencodeinitiative.php.checks; -import java.io.File; - import org.junit.Test; import org.sonar.plugins.php.api.tests.PHPCheckTest; import org.sonar.plugins.php.api.tests.PhpTestFile; -/** - * Test class to test the check implementation. - */ +import java.io.File; + public class AvoidUsingGlobalVariablesCheckTest { @Test diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/IncrementCheckTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/IncrementCheckTest.java index 08e364ab2..7da3216e5 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/IncrementCheckTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/IncrementCheckTest.java @@ -1,22 +1,3 @@ -/* - * SonarQube PHP Custom Rules Example - * Copyright (C) 2016-2016 SonarSource SA - * mailto:contact AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ package fr.greencodeinitiative.php.checks; import java.io.File; @@ -25,9 +6,6 @@ import org.sonar.plugins.php.api.tests.PHPCheckTest; import org.sonar.plugins.php.api.tests.PhpTestFile; -/** - * Test class to test the check implementation. - */ public class IncrementCheckTest { @Test diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonPlugin.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonPlugin.java index 73678cb08..cb8012554 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonPlugin.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonPlugin.java @@ -1,7 +1,5 @@ /* - * SonarQube Python Plugin - * Copyright (C) 2012-2019 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.python; diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java index 2fb5938de..2718b28f0 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java @@ -1,7 +1,5 @@ /* - * SonarQube Python Plugin - * Copyright (C) 2012-2019 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,12 +11,17 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.python; +import fr.greencodeinitiative.python.checks.*; +import org.sonar.api.rules.RuleType; +import org.sonar.api.server.rule.RulesDefinition; +import org.sonar.api.server.rule.RulesDefinitionAnnotationLoader; +import org.sonar.plugins.python.api.PythonCustomRuleRepository; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -29,14 +32,6 @@ import java.util.List; import java.util.Map; - -import fr.greencodeinitiative.python.checks.*; -import org.apache.commons.lang.StringUtils; -import org.sonar.api.rules.RuleType; -import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.api.server.rule.RulesDefinitionAnnotationLoader; -import org.sonar.plugins.python.api.PythonCustomRuleRepository; - public class PythonRuleRepository implements RulesDefinition, PythonCustomRuleRepository { public static final String LANGUAGE = "py"; diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/package-info.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/package-info.java deleted file mode 100644 index 63be179f7..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube Python Plugin - * Copyright (C) 2012-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -@ParametersAreNonnullByDefault -package fr.greencodeinitiative.python.checks; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/package-info.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/package-info.java index 58299e2f7..51a7a570e 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/package-info.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/package-info.java @@ -1,7 +1,5 @@ /* - * SonarQube Python Plugin - * Copyright (C) 2012-2019 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ @ParametersAreNonnullByDefault package fr.greencodeinitiative.python; diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java index 2d22fcbbf..477f5d4bb 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java @@ -1,7 +1,5 @@ /* - * SonarQube Python Plugin - * Copyright (C) 2012-2019 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.python; diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java index c21cc4fc8..828447a4d 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java @@ -1,7 +1,5 @@ /* - * SonarQube Python Plugin - * Copyright (C) 2012-2019 SonarSource SA - * mailto:info AT sonarsource DOT com + * Copyright (C) 2023 Green Code Initiative * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ package fr.greencodeinitiative.python; From 1ea04ef412435c729b5b8393f16325dcd5c69309 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 4 Jul 2023 16:00:28 +0200 Subject: [PATCH 102/170] prepare release 1.3.0 --- docker-compose.yml | 16 ++++++++-------- java-plugin/pom.xml | 2 +- javascript-plugin/pom.xml | 2 +- php-plugin/pom.xml | 2 +- pom.xml | 2 +- python-plugin/pom.xml | 2 +- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 32a7dc027..323680ce9 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,17 +16,17 @@ services: SONAR_ES_BOOTSTRAP_CHECKS_DISABLE: 'true' volumes: - type: bind - source: ./java-plugin/target/ecocode-java-plugin-1.2.2-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.2.2-SNAPSHOT.jar + source: ./java-plugin/target/ecocode-java-plugin-1.3.0-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.3.0-SNAPSHOT.jar - type: bind - source: ./javascript-plugin/target/ecocode-javascript-plugin-1.2.2-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-javascript-plugin-1.2.2-SNAPSHOT.jar + source: ./javascript-plugin/target/ecocode-javascript-plugin-1.3.0-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-javascript-plugin-1.3.0-SNAPSHOT.jar - type: bind - source: ./php-plugin/target/ecocode-php-plugin-1.2.2-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.2.2-SNAPSHOT.jar + source: ./php-plugin/target/ecocode-php-plugin-1.3.0-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.3.0-SNAPSHOT.jar - type: bind - source: ./python-plugin/target/ecocode-python-plugin-1.2.2-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-python-plugin-1.2.2-SNAPSHOT.jar + source: ./python-plugin/target/ecocode-python-plugin-1.3.0-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-python-plugin-1.3.0-SNAPSHOT.jar - "extensions:/opt/sonarqube/extensions" - "logs:/opt/sonarqube/logs" - "data:/opt/sonarqube/data" diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index c750fd98e..effb09efe 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.2-SNAPSHOT + 1.3.0-SNAPSHOT ecocode-java-plugin diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml index ab0c3a81c..1090559a7 100644 --- a/javascript-plugin/pom.xml +++ b/javascript-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.2-SNAPSHOT + 1.3.0-SNAPSHOT ecocode-javascript-plugin diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index ad70f265d..5178b94c7 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.2-SNAPSHOT + 1.3.0-SNAPSHOT ecocode-php-plugin diff --git a/pom.xml b/pom.xml index bead6defc..89a8e9e02 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ io.ecocode ecocode-parent - 1.2.2-SNAPSHOT + 1.3.0-SNAPSHOT pom ecoCode Sonar Plugins Project diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index 7fd808178..4cea8b683 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.2.2-SNAPSHOT + 1.3.0-SNAPSHOT ecocode-python-plugin From 11727fcf3d9ffa0b5e17d277ad042168f8e183bf Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 4 Jul 2023 16:01:10 +0200 Subject: [PATCH 103/170] [maven-release-plugin] prepare release 1.3.0 --- java-plugin/pom.xml | 2 +- javascript-plugin/pom.xml | 2 +- php-plugin/pom.xml | 2 +- pom.xml | 4 ++-- python-plugin/pom.xml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index effb09efe..ed52711cb 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.0-SNAPSHOT + 1.3.0 ecocode-java-plugin diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml index 1090559a7..ea8deccff 100644 --- a/javascript-plugin/pom.xml +++ b/javascript-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.0-SNAPSHOT + 1.3.0 ecocode-javascript-plugin diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index 5178b94c7..046d66088 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.0-SNAPSHOT + 1.3.0 ecocode-php-plugin diff --git a/pom.xml b/pom.xml index 89a8e9e02..461ca2f2f 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ io.ecocode ecocode-parent - 1.3.0-SNAPSHOT + 1.3.0 pom ecoCode Sonar Plugins Project @@ -33,7 +33,7 @@ scm:git:https://github.com/green-code-initiative/ecocode scm:git:https://github.com/green-code-initiative/ecocode https://github.com/green-code-initiative/ecocode - HEAD + 1.3.0 GitHub diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index 4cea8b683..d6ccb1731 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.0-SNAPSHOT + 1.3.0 ecocode-python-plugin From 726a5ee677eb5175f675215f1fcd481456a7a64e Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 4 Jul 2023 16:01:10 +0200 Subject: [PATCH 104/170] [maven-release-plugin] prepare for next development iteration --- java-plugin/pom.xml | 2 +- javascript-plugin/pom.xml | 2 +- php-plugin/pom.xml | 2 +- pom.xml | 4 ++-- python-plugin/pom.xml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index ed52711cb..0a956e82e 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.0 + 1.3.1-SNAPSHOT ecocode-java-plugin diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml index ea8deccff..d9d7e5519 100644 --- a/javascript-plugin/pom.xml +++ b/javascript-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.0 + 1.3.1-SNAPSHOT ecocode-javascript-plugin diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index 046d66088..29f2e31b3 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.0 + 1.3.1-SNAPSHOT ecocode-php-plugin diff --git a/pom.xml b/pom.xml index 461ca2f2f..7b1750006 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ io.ecocode ecocode-parent - 1.3.0 + 1.3.1-SNAPSHOT pom ecoCode Sonar Plugins Project @@ -33,7 +33,7 @@ scm:git:https://github.com/green-code-initiative/ecocode scm:git:https://github.com/green-code-initiative/ecocode https://github.com/green-code-initiative/ecocode - 1.3.0 + HEAD GitHub diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index d6ccb1731..3447d148a 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.0 + 1.3.1-SNAPSHOT ecocode-python-plugin From 73a270d8c3998569faf3975de2e37b242f404dfc Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 4 Jul 2023 16:14:26 +0200 Subject: [PATCH 105/170] update docker-compose for next snapshot + correction CHANGELOG for 1.3.0 --- CHANGELOG.md | 21 +++++++++++---------- docker-compose.yml | 16 ++++++++-------- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 75f628259..42fc0e43e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +### Changed + +### Deleted + +## [1.3.0] - 2023-07-04 + +### Added + - [#108](https://github.com/green-code-initiative/ecoCode/issues/108) new Python rule EC66 : Use single quote (') instead of quotation mark (") - [#109](https://github.com/green-code-initiative/ecoCode/issues/109) new PHP rule EC3 : Getting the size of the collection in the loop. For further [RULES.md](./RULES.md) file - [#113](https://github.com/green-code-initiative/ecoCode/issues/113) new Python rule EC10 : Use unoptimized vector images @@ -26,18 +34,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#201](https://github.com/green-code-initiative/ecoCode/pull/201) Clean-up plugins and dependencies - technical : upgrade of maven plugins versions -### Deleted - ## [1.2.1] - 2023-04-18 -### Added - ### Changed - [#180](https://github.com/green-code-initiative/ecoCode/pull/180) correction of SonarQube review for MarketPlace (sonar plugin) -### Deleted - ## [1.2.0] - 2023-04-14 ### Added @@ -51,8 +53,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#167](https://github.com/green-code-initiative/ecoCode/issues/167) Use same kind for rules across different languages - [#173](https://github.com/green-code-initiative/ecoCode/issues/173) Update issue description of rule EC34 (try-catch) -### Deleted - ## [1.1.0] - 2023-04-03 ### Changed @@ -141,7 +141,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - First official release of ecocode plugins : java plugin, php plugin and python plugin -[unreleased]: https://github.com/green-code-initiative/ecoCode/compare/v1.2.1...HEAD +[unreleased]: https://github.com/green-code-initiative/ecoCode/compare/v1.3.0...HEAD + +[1.3.0]: https://github.com/green-code-initiative/ecoCode/compare/v1.2.1...v1.3.0 [1.2.1]: https://github.com/green-code-initiative/ecoCode/compare/v1.2.0...v1.2.1 @@ -160,4 +162,3 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [0.1.1]: https://github.com/green-code-initiative/ecoCode/compare/v0.1.0...v0.1.1 [0.1.0]: https://github.com/green-code-initiative/ecoCode/releases/tag/v0.1.0 - diff --git a/docker-compose.yml b/docker-compose.yml index 323680ce9..76f87d1ce 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,17 +16,17 @@ services: SONAR_ES_BOOTSTRAP_CHECKS_DISABLE: 'true' volumes: - type: bind - source: ./java-plugin/target/ecocode-java-plugin-1.3.0-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.3.0-SNAPSHOT.jar + source: ./java-plugin/target/ecocode-java-plugin-1.3.1-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.3.1-SNAPSHOT.jar - type: bind - source: ./javascript-plugin/target/ecocode-javascript-plugin-1.3.0-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-javascript-plugin-1.3.0-SNAPSHOT.jar + source: ./javascript-plugin/target/ecocode-javascript-plugin-1.3.1-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-javascript-plugin-1.3.1-SNAPSHOT.jar - type: bind - source: ./php-plugin/target/ecocode-php-plugin-1.3.0-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.3.0-SNAPSHOT.jar + source: ./php-plugin/target/ecocode-php-plugin-1.3.1-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.3.1-SNAPSHOT.jar - type: bind - source: ./python-plugin/target/ecocode-python-plugin-1.3.0-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-python-plugin-1.3.0-SNAPSHOT.jar + source: ./python-plugin/target/ecocode-python-plugin-1.3.1-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-python-plugin-1.3.1-SNAPSHOT.jar - "extensions:/opt/sonarqube/extensions" - "logs:/opt/sonarqube/logs" - "data:/opt/sonarqube/data" From cdcb3f2ae38871643a0e6c67585076d2ffd79f4b Mon Sep 17 00:00:00 2001 From: jycr Date: Wed, 12 Apr 2023 03:28:25 +0200 Subject: [PATCH 106/170] green-code-initiative/ecoCode#92 feat(rule): Creates module `ecocode-rules-specifications` --- ecocode-rules-specifications/README.md | 15 +++ ecocode-rules-specifications/pom.xml | 139 +++++++++++++++++++++++++ pom.xml | 1 + 3 files changed, 155 insertions(+) create mode 100644 ecocode-rules-specifications/README.md create mode 100644 ecocode-rules-specifications/pom.xml diff --git a/ecocode-rules-specifications/README.md b/ecocode-rules-specifications/README.md new file mode 100644 index 000000000..1ee24ba52 --- /dev/null +++ b/ecocode-rules-specifications/README.md @@ -0,0 +1,15 @@ +# ecoCode rules specification repository + +## Description + +This project contains the specifications of the ecoCode rules. + +All the existing rules can be found in the [rules folder](src/main/rules). + +## Description language + +The description of the rules uses the ASCIIDOC format (with [Markdown compatibility](https://docs.asciidoctor.org/asciidoc/latest/syntax-quick-reference/#markdown-compatibility)) in order to allow the inclusion of other pages (this feature is not available in standard with Markdown). + +See: +* [AsciiDoc Syntax Quick Reference](https://docs.asciidoctor.org/asciidoc/latest/syntax-quick-reference/) +* [Compare AsciiDoc to Markdown](https://docs.asciidoctor.org/asciidoc/latest/asciidoc-vs-markdown/) diff --git a/ecocode-rules-specifications/pom.xml b/ecocode-rules-specifications/pom.xml new file mode 100644 index 000000000..a85c3934d --- /dev/null +++ b/ecocode-rules-specifications/pom.xml @@ -0,0 +1,139 @@ + + + 4.0.0 + + + io.ecocode + ecocode-parent + 1.3.1-SNAPSHOT + + + ecocode-rules-specifications + + ecoCode Rules Specifications repository + Repository that contains the specifications of every static-analysis rules available in ecoCode plugins. + https://github.com/green-code-initiative/ecoCode/tree/main/ecocode-rules-specifications + + + + org.sonarsource.sonarqube + sonar-plugin-api + provided + + + org.sonarsource.analyzer-commons + sonar-analyzer-commons + + + + org.junit.jupiter + junit-jupiter + test + + + + org.assertj + assertj-core + test + + + + + + + org.jacoco + jacoco-maven-plugin + + + prepare-agent + + prepare-agent + + + + report + + report + + + + + + + org.asciidoctor + asciidoctor-maven-plugin + 2.2.4 + + + convert-to-html + generate-resources + + process-asciidoc + + + ${project.basedir}/src/main/rules + ${project.build.directory}/rules + + coderay + style + + true + false + true + + + ERROR + + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 3.1.0 + + + process-resources + + run + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.6.0 + + + + true + + + + + diff --git a/pom.xml b/pom.xml index 7b1750006..0a13b79b0 100644 --- a/pom.xml +++ b/pom.xml @@ -23,6 +23,7 @@ + ecocode-rules-specifications python-plugin java-plugin javascript-plugin From a8d9f34cd3040b790aa7c7ddf882400fa932a3e2 Mon Sep 17 00:00:00 2001 From: jycr Date: Wed, 12 Apr 2023 03:28:58 +0200 Subject: [PATCH 107/170] green-code-initiative/ecoCode#92 refactor(rule/java): moves Java rules into `ecocode-rules-specifications` module --- ecocode-rules-specifications/pom.xml | 23 +++++++ .../src/main/assembly/java.xml | 18 +++++ .../src/main/rules/EC1}/EC1.json | 0 .../src/main/rules/EC1/java/EC1.asciidoc | 0 .../src/main/rules/EC2}/EC2.json | 0 .../src/main/rules/EC2/java/EC2.asciidoc | 0 .../src/main/rules/EC27}/EC27.json | 0 .../src/main/rules/EC27/java/EC27.asciidoc | 0 .../src/main/rules/EC28}/EC28.json | 0 .../src/main/rules/EC28/java/EC28.asciidoc | 0 .../src/main/rules/EC3}/EC3.json | 0 .../src/main/rules/EC3/java/EC3.asciidoc | 0 .../src/main/rules/EC32}/EC32.json | 0 .../src/main/rules/EC32/java/EC32.asciidoc | 0 .../src/main/rules/EC4}/EC4.json | 0 .../src/main/rules/EC4/java/EC4.asciidoc | 0 .../src/main/rules/EC5}/EC5.json | 0 .../src/main/rules/EC5/java/EC5.asciidoc | 0 .../src/main/rules/EC53}/EC53.json | 0 .../src/main/rules/EC53/java/EC53.asciidoc | 0 .../src/main/rules/EC63}/EC63.json | 0 .../src/main/rules/EC63/java/EC63.asciidoc | 0 .../src/main/rules/EC67}/EC67.json | 0 .../src/main/rules/EC67/java/EC67.asciidoc | 0 .../src/main/rules/EC69}/EC69.json | 0 .../src/main/rules/EC69/java/EC69.asciidoc | 0 .../src/main/rules/EC72}/EC72.json | 0 .../src/main/rules/EC72/java/EC72.asciidoc | 0 .../src/main/rules/EC74}/EC74.json | 0 .../src/main/rules/EC74/java/EC74.asciidoc | 0 .../src/main/rules/EC75}/EC75.json | 0 .../src/main/rules/EC75/java/EC75.asciidoc | 0 .../src/main/rules/EC76}/EC76.json | 0 .../src/main/rules/EC76/java/EC76.asciidoc | 0 .../src/main/rules/EC77}/EC77.json | 0 .../src/main/rules/EC77/java/EC77.asciidoc | 0 .../src/main/rules/EC78}/EC78.json | 0 .../src/main/rules/EC78/java/EC78.asciidoc | 0 .../src/main/rules/EC79}/EC79.json | 0 .../src/main/rules/EC79/java/EC79.asciidoc | 0 java-plugin/pom.xml | 13 ++-- .../java/JavaCheckRegistrar.java | 45 ++++++++++++- .../java/JavaRulesDefinition.java | 32 +++------ .../greencodeinitiative/java/RulesList.java | 66 ------------------- .../java/JavaPluginTest.java | 12 ++-- .../java/JavaRulesDefinitionTest.java | 65 +++++++++++++----- 46 files changed, 156 insertions(+), 118 deletions(-) create mode 100644 ecocode-rules-specifications/src/main/assembly/java.xml rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC1}/EC1.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC1.html => ecocode-rules-specifications/src/main/rules/EC1/java/EC1.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC2}/EC2.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC2.html => ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC27}/EC27.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC27.html => ecocode-rules-specifications/src/main/rules/EC27/java/EC27.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC28}/EC28.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC28.html => ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC3}/EC3.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC3.html => ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC32}/EC32.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC32.html => ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC4}/EC4.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC4.html => ecocode-rules-specifications/src/main/rules/EC4/java/EC4.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC5}/EC5.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC5.html => ecocode-rules-specifications/src/main/rules/EC5/java/EC5.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC53}/EC53.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC53.html => ecocode-rules-specifications/src/main/rules/EC53/java/EC53.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC63}/EC63.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC63.html => ecocode-rules-specifications/src/main/rules/EC63/java/EC63.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC67}/EC67.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC67.html => ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC69}/EC69.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC69.html => ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC72}/EC72.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC72.html => ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC74}/EC74.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC74.html => ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC75}/EC75.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC75.html => ecocode-rules-specifications/src/main/rules/EC75/java/EC75.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC76}/EC76.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC76.html => ecocode-rules-specifications/src/main/rules/EC76/java/EC76.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC77}/EC77.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC77.html => ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC78}/EC78.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC78.html => ecocode-rules-specifications/src/main/rules/EC78/java/EC78.asciidoc (100%) rename {java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java => ecocode-rules-specifications/src/main/rules/EC79}/EC79.json (100%) rename java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC79.html => ecocode-rules-specifications/src/main/rules/EC79/java/EC79.asciidoc (100%) delete mode 100644 java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java diff --git a/ecocode-rules-specifications/pom.xml b/ecocode-rules-specifications/pom.xml index a85c3934d..99ed2b78d 100644 --- a/ecocode-rules-specifications/pom.xml +++ b/ecocode-rules-specifications/pom.xml @@ -110,6 +110,17 @@ run + + + + + + + + + + + @@ -129,6 +140,18 @@ maven-assembly-plugin 3.6.0 + + assembly-java + prepare-package + + single + + + + ${project.basedir}/src/main/assembly/java.xml + + + true diff --git a/ecocode-rules-specifications/src/main/assembly/java.xml b/ecocode-rules-specifications/src/main/assembly/java.xml new file mode 100644 index 000000000..dc9d8bd3c --- /dev/null +++ b/ecocode-rules-specifications/src/main/assembly/java.xml @@ -0,0 +1,18 @@ + + java + + jar + + false + + + ${project.build.outputDirectory} + + io/ecocode/rules/java/*.* + + + + + diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC1.json b/ecocode-rules-specifications/src/main/rules/EC1/EC1.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC1.json rename to ecocode-rules-specifications/src/main/rules/EC1/EC1.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC1.html b/ecocode-rules-specifications/src/main/rules/EC1/java/EC1.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC1.html rename to ecocode-rules-specifications/src/main/rules/EC1/java/EC1.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC2.json b/ecocode-rules-specifications/src/main/rules/EC2/EC2.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC2.json rename to ecocode-rules-specifications/src/main/rules/EC2/EC2.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC2.html b/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC2.html rename to ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC27.json b/ecocode-rules-specifications/src/main/rules/EC27/EC27.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC27.json rename to ecocode-rules-specifications/src/main/rules/EC27/EC27.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC27.html b/ecocode-rules-specifications/src/main/rules/EC27/java/EC27.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC27.html rename to ecocode-rules-specifications/src/main/rules/EC27/java/EC27.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC28.json b/ecocode-rules-specifications/src/main/rules/EC28/EC28.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC28.json rename to ecocode-rules-specifications/src/main/rules/EC28/EC28.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC28.html b/ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC28.html rename to ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC3.json b/ecocode-rules-specifications/src/main/rules/EC3/EC3.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC3.json rename to ecocode-rules-specifications/src/main/rules/EC3/EC3.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC3.html b/ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC3.html rename to ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC32.json b/ecocode-rules-specifications/src/main/rules/EC32/EC32.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC32.json rename to ecocode-rules-specifications/src/main/rules/EC32/EC32.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC32.html b/ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC32.html rename to ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC4.json b/ecocode-rules-specifications/src/main/rules/EC4/EC4.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC4.json rename to ecocode-rules-specifications/src/main/rules/EC4/EC4.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC4.html b/ecocode-rules-specifications/src/main/rules/EC4/java/EC4.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC4.html rename to ecocode-rules-specifications/src/main/rules/EC4/java/EC4.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC5.json b/ecocode-rules-specifications/src/main/rules/EC5/EC5.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC5.json rename to ecocode-rules-specifications/src/main/rules/EC5/EC5.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC5.html b/ecocode-rules-specifications/src/main/rules/EC5/java/EC5.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC5.html rename to ecocode-rules-specifications/src/main/rules/EC5/java/EC5.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC53.json b/ecocode-rules-specifications/src/main/rules/EC53/EC53.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC53.json rename to ecocode-rules-specifications/src/main/rules/EC53/EC53.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC53.html b/ecocode-rules-specifications/src/main/rules/EC53/java/EC53.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC53.html rename to ecocode-rules-specifications/src/main/rules/EC53/java/EC53.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC63.json b/ecocode-rules-specifications/src/main/rules/EC63/EC63.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC63.json rename to ecocode-rules-specifications/src/main/rules/EC63/EC63.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC63.html b/ecocode-rules-specifications/src/main/rules/EC63/java/EC63.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC63.html rename to ecocode-rules-specifications/src/main/rules/EC63/java/EC63.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC67.json b/ecocode-rules-specifications/src/main/rules/EC67/EC67.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC67.json rename to ecocode-rules-specifications/src/main/rules/EC67/EC67.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC67.html b/ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC67.html rename to ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC69.json b/ecocode-rules-specifications/src/main/rules/EC69/EC69.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC69.json rename to ecocode-rules-specifications/src/main/rules/EC69/EC69.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC69.html b/ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC69.html rename to ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC72.json b/ecocode-rules-specifications/src/main/rules/EC72/EC72.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC72.json rename to ecocode-rules-specifications/src/main/rules/EC72/EC72.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC72.html b/ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC72.html rename to ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC74.json b/ecocode-rules-specifications/src/main/rules/EC74/EC74.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC74.json rename to ecocode-rules-specifications/src/main/rules/EC74/EC74.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC74.html b/ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC74.html rename to ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC75.json b/ecocode-rules-specifications/src/main/rules/EC75/EC75.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC75.json rename to ecocode-rules-specifications/src/main/rules/EC75/EC75.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC75.html b/ecocode-rules-specifications/src/main/rules/EC75/java/EC75.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC75.html rename to ecocode-rules-specifications/src/main/rules/EC75/java/EC75.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC76.json b/ecocode-rules-specifications/src/main/rules/EC76/EC76.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC76.json rename to ecocode-rules-specifications/src/main/rules/EC76/EC76.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC76.html b/ecocode-rules-specifications/src/main/rules/EC76/java/EC76.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC76.html rename to ecocode-rules-specifications/src/main/rules/EC76/java/EC76.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC77.json b/ecocode-rules-specifications/src/main/rules/EC77/EC77.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC77.json rename to ecocode-rules-specifications/src/main/rules/EC77/EC77.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC77.html b/ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC77.html rename to ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC78.json b/ecocode-rules-specifications/src/main/rules/EC78/EC78.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC78.json rename to ecocode-rules-specifications/src/main/rules/EC78/EC78.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC78.html b/ecocode-rules-specifications/src/main/rules/EC78/java/EC78.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC78.html rename to ecocode-rules-specifications/src/main/rules/EC78/java/EC78.asciidoc diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC79.json b/ecocode-rules-specifications/src/main/rules/EC79/EC79.json similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC79.json rename to ecocode-rules-specifications/src/main/rules/EC79/EC79.json diff --git a/java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC79.html b/ecocode-rules-specifications/src/main/rules/EC79/java/EC79.asciidoc similarity index 100% rename from java-plugin/src/main/resources/fr/greencodeinitiative/l10n/java/rules/java/EC79.html rename to ecocode-rules-specifications/src/main/rules/EC79/java/EC79.asciidoc diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index 0a956e82e..2f4e2476b 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -16,21 +16,24 @@ https://github.com/green-code-initiative/ecoCode/tree/main/java-plugin + + ${project.groupId} + ecocode-rules-specifications + ${project.version} + java + org.sonarsource.java sonar-java-plugin sonar-plugin + provided org.sonarsource.sonarqube sonar-plugin-api - - - - org.sonarsource.analyzer-commons - sonar-analyzer-commons + provided diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java index 5705e6ec5..5ca219399 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java @@ -16,8 +16,28 @@ */ package fr.greencodeinitiative.java; +import java.util.Collections; import java.util.List; +import fr.greencodeinitiative.java.checks.ArrayCopyCheck; +import fr.greencodeinitiative.java.checks.AvoidConcatenateStringsInLoop; +import fr.greencodeinitiative.java.checks.AvoidFullSQLRequest; +import fr.greencodeinitiative.java.checks.AvoidGettingSizeCollectionInLoop; +import fr.greencodeinitiative.java.checks.AvoidMultipleIfElseStatement; +import fr.greencodeinitiative.java.checks.AvoidRegexPatternNotStatic; +import fr.greencodeinitiative.java.checks.AvoidSQLRequestInLoop; +import fr.greencodeinitiative.java.checks.AvoidSetConstantInBatchUpdate; +import fr.greencodeinitiative.java.checks.AvoidSpringRepositoryCallInLoopCheck; +import fr.greencodeinitiative.java.checks.AvoidStatementForDMLQueries; +import fr.greencodeinitiative.java.checks.AvoidUsageOfStaticCollections; +import fr.greencodeinitiative.java.checks.AvoidUsingGlobalVariablesCheck; +import fr.greencodeinitiative.java.checks.FreeResourcesOfAutoCloseableInterface; +import fr.greencodeinitiative.java.checks.IncrementCheck; +import fr.greencodeinitiative.java.checks.InitializeBufferWithAppropriateSize; +import fr.greencodeinitiative.java.checks.NoFunctionCallWhenDeclaringForLoop; +import fr.greencodeinitiative.java.checks.OptimizeReadFileExceptions; +import fr.greencodeinitiative.java.checks.UnnecessarilyAssignValuesToVariables; +import fr.greencodeinitiative.java.checks.UseCorrectForLoop; import org.sonar.plugins.java.api.CheckRegistrar; import org.sonar.plugins.java.api.JavaCheck; import org.sonarsource.api.sonarlint.SonarLintSide; @@ -30,6 +50,27 @@ */ @SonarLintSide public class JavaCheckRegistrar implements CheckRegistrar { + private static final List> ANNOTATED_RULE_CLASSES = List.of( + ArrayCopyCheck.class, + IncrementCheck.class, + AvoidConcatenateStringsInLoop.class, + AvoidUsageOfStaticCollections.class, + AvoidGettingSizeCollectionInLoop.class, + AvoidRegexPatternNotStatic.class, + NoFunctionCallWhenDeclaringForLoop.class, + AvoidStatementForDMLQueries.class, + AvoidSpringRepositoryCallInLoopCheck.class, + AvoidSQLRequestInLoop.class, + AvoidFullSQLRequest.class, + UseCorrectForLoop.class, + UnnecessarilyAssignValuesToVariables.class, + OptimizeReadFileExceptions.class, + InitializeBufferWithAppropriateSize.class, + AvoidUsingGlobalVariablesCheck.class, + AvoidSetConstantInBatchUpdate.class, + FreeResourcesOfAutoCloseableInterface.class, + AvoidMultipleIfElseStatement.class + ); /** * Register the classes that will be used to instantiate checks during analysis. @@ -44,13 +85,13 @@ public void register(RegistrarContext registrarContext) { * Lists all the main checks provided by the plugin */ public static List> checkClasses() { - return RulesList.getJavaChecks(); + return ANNOTATED_RULE_CLASSES; } /** * Lists all the test checks provided by the plugin */ public static List> testCheckClasses() { - return RulesList.getJavaTestChecks(); + return Collections.emptyList(); } } diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java index 56324e89e..e8f7cccd3 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java @@ -16,30 +16,22 @@ */ package fr.greencodeinitiative.java; +import java.util.ArrayList; + import org.sonar.api.SonarRuntime; import org.sonar.api.server.rule.RulesDefinition; import org.sonarsource.analyzer.commons.RuleMetadataLoader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Objects; -import java.util.Set; - /** * Declare rule metadata in server repository of rules. * That allows to list the rules in the page "Rules". */ public class JavaRulesDefinition implements RulesDefinition { + private static final String RESOURCE_BASE_PATH = "io/ecocode/rules/java"; - // don't change that because the path is hard coded in CheckVerifier - private static final String RESOURCE_BASE_PATH = "fr/greencodeinitiative/l10n/java/rules/java"; - - - // Add the rule keys of the rules which need to be considered as template-rules - private static final Set RULE_TEMPLATES_KEY = Collections.emptySet(); - public static final String NAME = "ecoCode"; - public static final String LANGUAGE = "java"; - public static final String REPOSITORY_KEY = "ecocode-java"; + private static final String NAME = "ecoCode"; + private static final String LANGUAGE = "java"; + static final String REPOSITORY_KEY = "ecocode-java"; private final SonarRuntime sonarRuntime; @@ -53,17 +45,11 @@ public void define(Context context) { RuleMetadataLoader ruleMetadataLoader = new RuleMetadataLoader(RESOURCE_BASE_PATH, sonarRuntime); - ruleMetadataLoader.addRulesByAnnotatedClass(repository, new ArrayList<>(RulesList.getChecks())); - - setTemplates(repository); - + ruleMetadataLoader.addRulesByAnnotatedClass(repository, new ArrayList<>(JavaCheckRegistrar.checkClasses())); repository.done(); } - private static void setTemplates(NewRepository repository) { - RULE_TEMPLATES_KEY.stream() - .map(repository::rule) - .filter(Objects::nonNull) - .forEach(rule -> rule.setTemplate(true)); + public String repositoryKey() { + return REPOSITORY_KEY; } } diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java deleted file mode 100644 index 850e141c7..000000000 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/RulesList.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2023 Green Code Initiative - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.java; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import fr.greencodeinitiative.java.checks.*; -import org.sonar.plugins.java.api.JavaCheck; - -public final class RulesList { - - private RulesList() { - } - - public static List> getChecks() { - List> checks = new ArrayList<>(); - checks.addAll(getJavaChecks()); - checks.addAll(getJavaTestChecks()); - return Collections.unmodifiableList(checks); - } - - public static List> getJavaChecks() { - return Collections.unmodifiableList(Arrays.asList( - ArrayCopyCheck.class, - IncrementCheck.class, - AvoidConcatenateStringsInLoop.class, - AvoidUsageOfStaticCollections.class, - AvoidGettingSizeCollectionInLoop.class, - AvoidRegexPatternNotStatic.class, - NoFunctionCallWhenDeclaringForLoop.class, - AvoidStatementForDMLQueries.class, - AvoidSpringRepositoryCallInLoopCheck.class, - AvoidSQLRequestInLoop.class, - AvoidFullSQLRequest.class, - UseCorrectForLoop.class, - UnnecessarilyAssignValuesToVariables.class, - OptimizeReadFileExceptions.class, - InitializeBufferWithAppropriateSize.class, - AvoidUsingGlobalVariablesCheck.class, - AvoidSetConstantInBatchUpdate.class, - FreeResourcesOfAutoCloseableInterface.class, - AvoidMultipleIfElseStatement.class - )); - } - - public static List> getJavaTestChecks() { - return Collections.emptyList(); - } -} diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java index c925ece4e..3d09e5b0e 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java @@ -16,6 +16,7 @@ */ package fr.greencodeinitiative.java; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.sonar.api.Plugin; import org.sonar.api.SonarRuntime; @@ -24,14 +25,17 @@ import static org.mockito.Mockito.mock; class JavaPluginTest { + private Plugin.Context context; - @Test - void testName() { + @BeforeEach + void init() { SonarRuntime sonarRuntime = mock(SonarRuntime.class); - Plugin.Context context = new Plugin.Context(sonarRuntime); - + context = new Plugin.Context(sonarRuntime); new JavaPlugin().define(context); + } + @Test + void test() { assertThat(context.getExtensions()).hasSize(2); } diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java index 20aabc21c..bb6f796d3 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java @@ -24,38 +24,65 @@ import org.sonar.api.rules.RuleType; import org.sonar.api.server.debt.DebtRemediationFunction.Type; import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.api.server.rule.RulesDefinition.Param; -import org.sonar.api.server.rule.RulesDefinition.Repository; import org.sonar.api.server.rule.RulesDefinition.Rule; import org.sonar.api.utils.Version; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; class JavaRulesDefinitionTest { private RulesDefinition.Repository repository; + private RulesDefinition.Context context; @BeforeEach void init() { - SonarRuntime sonarRuntime = mock(SonarRuntime.class); + // TODO: Remove this check after Git repo split + /* + On an IDE (like IntelliJ), if the developer runs the unit tests without building/generating the Maven goals on the + "ecocode-rules-specifications" module before, the unit tests will not see the generated HTML descriptions (from ASCIIDOC files). + The developer must therefore configure his IDE to build the `ecocode-rules-specifications` module before launching the Tests. + + When the `java-plugin` submodule is in a specific Git repository, `ecocode-rules-specifications` will be fetched from a classic + external Maven dependency. There will therefore no longer be any need to perform this specific configuration. + */ + if (JavaRulesDefinition.class.getResource("/io/ecocode/rules/java/EC4.json") == null) { + String message = "'ecocode-rules-specification' resources corrupted. Please check build of 'ecocode-rules-specification' module"; + if (System.getProperties().keySet().stream().anyMatch(k -> k.toString().startsWith("idea."))) { + message += "\n\nOn 'IntelliJ IDEA':" + + "\n1. go to settings :" + + "\n > Build, Execution, Deployment > Build Tools > Maven > Runner" + + "\n2. check option:" + + "\n > Delegate IDE build/run actions to Maven" + + "\n3. Click on menu: " + + "\n > Build > Build Project" + ; + } + fail(message); + } + + final SonarRuntime sonarRuntime = mock(SonarRuntime.class); doReturn(Version.create(0, 0)).when(sonarRuntime).getApiVersion(); JavaRulesDefinition rulesDefinition = new JavaRulesDefinition(sonarRuntime); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); - repository = context.repository(JavaRulesDefinition.REPOSITORY_KEY); + repository = context.repository(rulesDefinition.repositoryKey()); } @Test - void test() { - assertThat(repository.name()).isEqualTo(JavaRulesDefinition.NAME); - assertThat(repository.language()).isEqualTo(JavaRulesDefinition.LANGUAGE); - assertThat(repository.rules()).hasSize(RulesList.getChecks().size()); - assertThat(repository.rules().stream().filter(Rule::template)).isEmpty(); + @DisplayName("Test repository metadata") + void testMetadata() { + assertThat(repository.name()).isEqualTo("ecoCode"); + assertThat(repository.language()).isEqualTo("java"); + assertThat(repository.key()).isEqualTo("ecocode-java"); + assertThat(repository.rules()).hasSize(19); + } - assertRuleProperties(repository); - assertAllRuleParametersHaveDescription(repository); + @Test + void testRegistredRules() { + assertThat(repository.rules()).hasSize(19); } @Test @@ -68,7 +95,8 @@ void testRuleKeyPrefix() { assertions.assertAll(); } - private static void assertRuleProperties(Repository repository) { + @Test + void assertRuleProperties() { Rule rule = repository.rule("EC67"); assertThat(rule).isNotNull(); assertThat(rule.name()).isEqualTo("Use ++i instead of i++"); @@ -76,12 +104,13 @@ private static void assertRuleProperties(Repository repository) { assertThat(rule.type()).isEqualTo(RuleType.CODE_SMELL); } - private static void assertAllRuleParametersHaveDescription(Repository repository) { - for (Rule rule : repository.rules()) { - for (Param param : rule.params()) { - assertThat(param.description()).as("description for " + param.key()).isNotEmpty(); - } - } + @Test + void testAllRuleParametersHaveDescription() { + SoftAssertions assertions = new SoftAssertions(); + repository.rules().stream() + .flatMap(rule -> rule.params().stream()) + .forEach(param -> assertions.assertThat(param.description()).as("description for " + param.key()).isNotEmpty()); + assertions.assertAll(); } } From 080e79bf6ca14e101dec6ade8a91f19c450f7499 Mon Sep 17 00:00:00 2001 From: jycr Date: Fri, 14 Apr 2023 18:22:49 +0200 Subject: [PATCH 108/170] green-code-initiative/ecoCode#92 refactor(rule/php): moves PHP rules into `ecocode-rules-specifications` module --- ecocode-rules-specifications/pom.xml | 19 ++++ .../src/main/assembly/php.xml | 18 ++++ .../src/main/rules/EC22/EC22.json | 15 ++++ .../src/main/rules/EC22/php/EC22.asciidoc | 0 .../src/main/rules/EC3/php/EC3.asciidoc | 0 .../src/main/rules/EC34/EC34.json | 15 ++++ .../src/main/rules/EC34/php/EC34.asciidoc | 0 .../src/main/rules/EC4/php/EC4.asciidoc | 0 .../src/main/rules/EC66/EC66.json | 15 ++++ .../src/main/rules/EC66/php/EC66.asciidoc | 0 .../src/main/rules/EC67/php/EC67.asciidoc | 0 .../src/main/rules/EC69/php/EC69.asciidoc | 0 .../src/main/rules/EC72/php/EC72.asciidoc | 0 .../src/main/rules/EC74/php/EC74.asciidoc | 0 php-plugin/pom.xml | 28 +++++- .../php/PhpRuleRepository.java | 73 ++++----------- .../php/PhpPluginTest.java | 16 ++-- .../php/PhpRuleRepositoryTest.java | 90 ++++++++++++++----- 18 files changed, 202 insertions(+), 87 deletions(-) create mode 100644 ecocode-rules-specifications/src/main/assembly/php.xml create mode 100644 ecocode-rules-specifications/src/main/rules/EC22/EC22.json rename php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC22.html => ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc (100%) rename php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html => ecocode-rules-specifications/src/main/rules/EC3/php/EC3.asciidoc (100%) create mode 100644 ecocode-rules-specifications/src/main/rules/EC34/EC34.json rename php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC34.html => ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc (100%) rename php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC4.html => ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc (100%) create mode 100644 ecocode-rules-specifications/src/main/rules/EC66/EC66.json rename php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC66.html => ecocode-rules-specifications/src/main/rules/EC66/php/EC66.asciidoc (100%) rename php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC67.html => ecocode-rules-specifications/src/main/rules/EC67/php/EC67.asciidoc (100%) rename php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC69.html => ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc (100%) rename php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC72.html => ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc (100%) rename php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC74.html => ecocode-rules-specifications/src/main/rules/EC74/php/EC74.asciidoc (100%) diff --git a/ecocode-rules-specifications/pom.xml b/ecocode-rules-specifications/pom.xml index 99ed2b78d..8c53609a4 100644 --- a/ecocode-rules-specifications/pom.xml +++ b/ecocode-rules-specifications/pom.xml @@ -119,6 +119,13 @@ + + + + + + + @@ -152,6 +159,18 @@ + + assembly-php + prepare-package + + single + + + + ${project.basedir}/src/main/assembly/php.xml + + + true diff --git a/ecocode-rules-specifications/src/main/assembly/php.xml b/ecocode-rules-specifications/src/main/assembly/php.xml new file mode 100644 index 000000000..83eb07521 --- /dev/null +++ b/ecocode-rules-specifications/src/main/assembly/php.xml @@ -0,0 +1,18 @@ + + php + + jar + + false + + + ${project.build.outputDirectory} + + io/ecocode/rules/php/*.* + + + + + diff --git a/ecocode-rules-specifications/src/main/rules/EC22/EC22.json b/ecocode-rules-specifications/src/main/rules/EC22/EC22.json new file mode 100644 index 000000000..9d3ed8c36 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC22/EC22.json @@ -0,0 +1,15 @@ +{ + "title": "Use of methods for basic operations", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "eco-design", + "performance", + "ecocode" + ], + "defaultSeverity": "Minor" +} diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC22.html b/ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc similarity index 100% rename from php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC22.html rename to ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html b/ecocode-rules-specifications/src/main/rules/EC3/php/EC3.asciidoc similarity index 100% rename from php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC3.html rename to ecocode-rules-specifications/src/main/rules/EC3/php/EC3.asciidoc diff --git a/ecocode-rules-specifications/src/main/rules/EC34/EC34.json b/ecocode-rules-specifications/src/main/rules/EC34/EC34.json new file mode 100644 index 000000000..4191cbb71 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC34/EC34.json @@ -0,0 +1,15 @@ +{ + "title": "Avoid using try-catch-finally statement", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "eco-design", + "performance", + "ecocode" + ], + "defaultSeverity": "Minor" +} diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC34.html b/ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc similarity index 100% rename from php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC34.html rename to ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC4.html b/ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc similarity index 100% rename from php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC4.html rename to ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc diff --git a/ecocode-rules-specifications/src/main/rules/EC66/EC66.json b/ecocode-rules-specifications/src/main/rules/EC66/EC66.json new file mode 100644 index 000000000..6ed6137dc --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC66/EC66.json @@ -0,0 +1,15 @@ +{ + "title": "Avoid using double quote (\"), prefer using simple quote (')", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "eco-design", + "performance", + "ecocode" + ], + "defaultSeverity": "Minor" +} diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC66.html b/ecocode-rules-specifications/src/main/rules/EC66/php/EC66.asciidoc similarity index 100% rename from php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC66.html rename to ecocode-rules-specifications/src/main/rules/EC66/php/EC66.asciidoc diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC67.html b/ecocode-rules-specifications/src/main/rules/EC67/php/EC67.asciidoc similarity index 100% rename from php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC67.html rename to ecocode-rules-specifications/src/main/rules/EC67/php/EC67.asciidoc diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC69.html b/ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc similarity index 100% rename from php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC69.html rename to ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC72.html b/ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc similarity index 100% rename from php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC72.html rename to ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC74.html b/ecocode-rules-specifications/src/main/rules/EC74/php/EC74.asciidoc similarity index 100% rename from php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC74.html rename to ecocode-rules-specifications/src/main/rules/EC74/php/EC74.asciidoc diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index 29f2e31b3..c034e7e3b 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -16,16 +16,24 @@ https://github.com/green-code-initiative/ecoCode/tree/main/php-plugin + + ${project.groupId} + ecocode-rules-specifications + ${project.version} + php + org.sonarsource.php sonar-php-plugin sonar-plugin + provided org.sonarsource.sonarqube sonar-plugin-api + provided @@ -35,6 +43,19 @@ + + + org.sonarsource.java + java-checks-testkit + test + + + + org.junit.jupiter + junit-jupiter + test + + org.assertj assertj-core @@ -62,10 +83,13 @@ true ${sonarqube.version} ${java.version} - ${sonarqube.version} - ${java.version} + + + org.apache.maven.plugins + maven-shade-plugin + org.apache.maven.plugins maven-dependency-plugin diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java index d0fd50e53..9c37e58e3 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java @@ -16,14 +16,7 @@ */ package fr.greencodeinitiative.php; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; import java.util.List; -import java.util.Map; import fr.greencodeinitiative.php.checks.AvoidGettingSizeCollectionInLoopCheck; import fr.greencodeinitiative.php.checks.AvoidDoubleQuoteCheck; @@ -34,48 +27,29 @@ import fr.greencodeinitiative.php.checks.IncrementCheck; import fr.greencodeinitiative.php.checks.NoFunctionCallWhenDeclaringForLoop; import fr.greencodeinitiative.php.checks.UseOfMethodsForBasicOperations; -import org.sonar.api.rules.RuleType; +import org.sonar.api.SonarRuntime; import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.api.server.rule.RulesDefinitionAnnotationLoader; import org.sonar.plugins.php.api.visitors.PHPCustomRuleRepository; +import org.sonarsource.analyzer.commons.RuleMetadataLoader; public class PhpRuleRepository implements RulesDefinition, PHPCustomRuleRepository { - public static final String LANGUAGE = "php"; - public static final String NAME = "ecoCode"; - public static final String RESOURCE_BASE_PATH = "/fr/greencodeinitiative/l10n/php/rules/custom/"; - public static final String REPOSITORY_KEY = "ecocode-php"; + private static final String LANGUAGE = "php"; + private static final String NAME = "ecoCode"; + private static final String RESOURCE_BASE_PATH = "io/ecocode/rules/php"; + private static final String REPOSITORY_KEY = "ecocode-php"; - @Override - public void define(Context context) { - NewRepository repository = context.createRepository(repositoryKey(), LANGUAGE).setName(NAME); - - new RulesDefinitionAnnotationLoader().load(repository, checkClasses().toArray(new Class[] {})); - - // technical debt - Map remediationCosts = new HashMap<>(); - remediationCosts.put(AvoidSQLRequestInLoopCheck.RULE_KEY, "10min"); - remediationCosts.put(AvoidFullSQLRequestCheck.RULE_KEY, "20min"); - repository.rules().forEach(rule -> { - rule.setType(RuleType.CODE_SMELL); - String debt = remediationCosts.get(rule.key()); - - // TODO DDC : create support to use org.apache.commons.lang.StringUtils -// if (StringUtils.isBlank(debt)) { - if (debt == null || debt.trim().equals("")) { - // default debt to 5min for issue correction - rule.setDebtRemediationFunction( - rule.debtRemediationFunctions().constantPerIssue("5min")); - } else { - rule.setDebtRemediationFunction( - rule.debtRemediationFunctions().constantPerIssue(debt)); - } - }); + private final SonarRuntime sonarRuntime; - // HTML description - repository.rules().forEach(rule -> - rule.setHtmlDescription(loadResource(RESOURCE_BASE_PATH + rule.key() + ".html"))); + public PhpRuleRepository(SonarRuntime sonarRuntime) { + this.sonarRuntime = sonarRuntime; + } + @Override + public void define(Context context) { + NewRepository repository = context.createRepository(REPOSITORY_KEY, LANGUAGE).setName(NAME); + RuleMetadataLoader ruleMetadataLoader = new RuleMetadataLoader(RESOURCE_BASE_PATH, sonarRuntime); + ruleMetadataLoader.addRulesByAnnotatedClass(repository, checkClasses()); repository.done(); } @@ -98,21 +72,4 @@ public List> checkClasses() { UseOfMethodsForBasicOperations.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); - } - } } diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java index 33736bc4c..9139c7c4e 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java @@ -16,20 +16,26 @@ */ package fr.greencodeinitiative.php; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.sonar.api.Plugin; import org.sonar.api.SonarRuntime; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; -public class PhpPluginTest { +class PhpPluginTest { + private Plugin.Context context; - @Test - public void test() { + @BeforeEach + void init() { SonarRuntime sonarRuntime = mock(SonarRuntime.class); - Plugin.Context context = new Plugin.Context(sonarRuntime); + context = new Plugin.Context(sonarRuntime); new PHPPlugin().define(context); + } + + @Test + void test() { assertThat(context.getExtensions()).hasSize(1); } diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java index 70ef4cae8..32495c4e1 100644 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java @@ -16,42 +16,88 @@ */ package fr.greencodeinitiative.php; -import static org.assertj.core.api.Assertions.assertThat; import org.assertj.core.api.SoftAssertions; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.sonar.api.SonarRuntime; import org.sonar.api.server.rule.RulesDefinition; +import org.sonar.api.utils.Version; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +class PhpRuleRepositoryTest { -public class PhpRuleRepositoryTest { + private RulesDefinition.Repository repository; - private PhpRuleRepository phpRuleRepository; - private RulesDefinition.Context context; + @BeforeEach + void init() { + // TODO: Remove this check after Git repo split + /* + On an IDE (like IntelliJ), if the developer runs the unit tests without building/generating the Maven goals on the + "ecocode-rules-specifications" module before, the unit tests will not see the generated HTML descriptions (from ASCIIDOC files). + The developer must therefore configure his IDE to build the `ecocode-rules-specifications` module before launching the Tests. + + When the `php-plugin` submodule is in a specific Git repository, `ecocode-rules-specifications` will be fetched from a classic + external Maven dependency. There will therefore no longer be any need to perform this specific configuration. + */ + if (PhpRuleRepository.class.getResource("/io/ecocode/rules/php/EC4.json") == null) { + String message = "'ecocode-rules-specification' resources corrupted. Please check build of 'ecocode-rules-specification' module"; + if (System.getProperties().keySet().stream().anyMatch(k -> k.toString().startsWith("idea."))) { + message += "\n\nOn 'IntelliJ IDEA':" + + "\n1. go to settings :" + + "\n > Build, Execution, Deployment > Build Tools > Maven > Runner" + + "\n2. check option:" + + "\n > Delegate IDE build/run actions to Maven" + + "\n3. Click on menu: " + + "\n > Build > Build Project" + ; + } + fail(message); + } + + final SonarRuntime sonarRuntime = mock(SonarRuntime.class); + doReturn(Version.create(0, 0)).when(sonarRuntime).getApiVersion(); + PhpRuleRepository rulesDefinition = new PhpRuleRepository(sonarRuntime); + RulesDefinition.Context context = new RulesDefinition.Context(); + rulesDefinition.define(context); + repository = context.repository(rulesDefinition.repositoryKey()); + } - @Before - public void init() { - phpRuleRepository = new PhpRuleRepository(); - context = new RulesDefinition.Context(); - phpRuleRepository.define(context); + @Test + @DisplayName("Test repository metadata") + void testMetadata() { + assertThat(repository.name()).isEqualTo("ecoCode"); + assertThat(repository.language()).isEqualTo("php"); + assertThat(repository.key()).isEqualTo("ecocode-php"); } @Test - public void test() { - assertThat(phpRuleRepository.repositoryKey()).isEqualTo(PhpRuleRepository.REPOSITORY_KEY); - assertThat(context.repositories()).hasSize(1).extracting("key").containsExactly(phpRuleRepository.repositoryKey()); - assertThat(context.repositories().get(0).rules()).hasSize(9); - assertThat(phpRuleRepository.checkClasses()).hasSize(9); + void testRegistredRules() { + assertThat(repository.rules()).hasSize(9); } - /** - * Check all rule keys must be prefixed by 'EC' - */ - @Test() - public void testRuleKeyPrefix() { - RulesDefinition.Repository repository = context.repository(PhpRuleRepository.REPOSITORY_KEY); + @Test + @DisplayName("All rule keys must be prefixed by 'EC'") + void testRuleKeyPrefix() { SoftAssertions assertions = new SoftAssertions(); repository.rules().forEach( rule -> assertions.assertThat(rule.key()).startsWith("EC") ); assertions.assertAll(); } + + @Test + void testAllRuleParametersHaveDescription() { + SoftAssertions assertions = new SoftAssertions(); + repository.rules().stream() + .flatMap(rule -> rule.params().stream()) + .forEach(param -> assertions.assertThat(param.description()) + .as("description for " + param.key()) + .isNotEmpty()); + assertions.assertAll(); + } } From 9f95b447709196c63b2466c10d43218d96f0a070 Mon Sep 17 00:00:00 2001 From: jycr Date: Fri, 14 Apr 2023 18:25:32 +0200 Subject: [PATCH 109/170] green-code-initiative/ecoCode#92 refactor(rule/python): moves Python rules into `ecocode-rules-specifications` module --- ecocode-rules-specifications/pom.xml | 19 ++++ .../src/main/assembly/python.xml | 18 ++++ .../src/main/rules/EC10/EC10.json | 14 +++ .../src/main/rules/EC10/python/EC10.asciidoc | 0 .../src/main/rules/EC203/EC203.json | 16 ++++ .../main/rules/EC203/python/EC203.asciidoc | 0 .../src/main/rules/EC34/python/EC34.asciidoc | 0 .../src/main/rules/EC4/python/EC4.asciidoc | 0 .../src/main/rules/EC404/EC404.json | 15 ++++ .../main/rules/EC404/python/EC404.asciidoc | 0 .../src/main/rules/EC66/python/EC66.asciidoc | 0 .../src/main/rules/EC69/python/EC69.asciidoc | 0 .../src/main/rules/EC7/EC7.json | 15 ++++ .../src/main/rules/EC7/python/EC7.asciidoc | 0 .../src/main/rules/EC72/python/EC72.asciidoc | 0 .../src/main/rules/EC74/python/EC74.asciidoc | 0 python-plugin/pom.xml | 13 +++ .../python/PythonRuleRepository.java | 67 +++----------- .../python/PythonPluginTest.java | 16 ++-- .../python/PythonRuleRepositoryTest.java | 87 ++++++++++++++----- 20 files changed, 198 insertions(+), 82 deletions(-) create mode 100644 ecocode-rules-specifications/src/main/assembly/python.xml create mode 100644 ecocode-rules-specifications/src/main/rules/EC10/EC10.json rename python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC10.html => ecocode-rules-specifications/src/main/rules/EC10/python/EC10.asciidoc (100%) create mode 100644 ecocode-rules-specifications/src/main/rules/EC203/EC203.json rename python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html => ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc (100%) rename python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC34.html => ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc (100%) rename python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC4.html => ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc (100%) create mode 100644 ecocode-rules-specifications/src/main/rules/EC404/EC404.json rename python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC404.html => ecocode-rules-specifications/src/main/rules/EC404/python/EC404.asciidoc (100%) rename python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC66.html => ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc (100%) rename python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC69.html => ecocode-rules-specifications/src/main/rules/EC69/python/EC69.asciidoc (100%) create mode 100644 ecocode-rules-specifications/src/main/rules/EC7/EC7.json rename python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC7.html => ecocode-rules-specifications/src/main/rules/EC7/python/EC7.asciidoc (100%) rename python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC72.html => ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc (100%) rename python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC74.html => ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc (100%) diff --git a/ecocode-rules-specifications/pom.xml b/ecocode-rules-specifications/pom.xml index 8c53609a4..30e3f07ce 100644 --- a/ecocode-rules-specifications/pom.xml +++ b/ecocode-rules-specifications/pom.xml @@ -126,6 +126,13 @@ + + + + + + + @@ -171,6 +178,18 @@ + + assembly-python + prepare-package + + single + + + + ${project.basedir}/src/main/assembly/python.xml + + + true diff --git a/ecocode-rules-specifications/src/main/assembly/python.xml b/ecocode-rules-specifications/src/main/assembly/python.xml new file mode 100644 index 000000000..7c294fd24 --- /dev/null +++ b/ecocode-rules-specifications/src/main/assembly/python.xml @@ -0,0 +1,18 @@ + + python + + jar + + false + + + ${project.build.outputDirectory} + + io/ecocode/rules/python/*.* + + + + + diff --git a/ecocode-rules-specifications/src/main/rules/EC10/EC10.json b/ecocode-rules-specifications/src/main/rules/EC10/EC10.json new file mode 100644 index 000000000..ec7fbffd9 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC10/EC10.json @@ -0,0 +1,14 @@ +{ + "title": "Avoid using unoptimized vector images", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "60min" + }, + "tags": [ + "eco-design", + "ecocode" + ], + "defaultSeverity": "Minor" +} diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC10.html b/ecocode-rules-specifications/src/main/rules/EC10/python/EC10.asciidoc similarity index 100% rename from python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC10.html rename to ecocode-rules-specifications/src/main/rules/EC10/python/EC10.asciidoc diff --git a/ecocode-rules-specifications/src/main/rules/EC203/EC203.json b/ecocode-rules-specifications/src/main/rules/EC203/EC203.json new file mode 100644 index 000000000..3f46aefd8 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC203/EC203.json @@ -0,0 +1,16 @@ +{ + "title": "Detect unoptimized image format", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "60min" + }, + "tags": [ + "performance", + "user-experience", + "eco-design", + "ecocode" + ], + "defaultSeverity": "Minor" +} diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html b/ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc similarity index 100% rename from python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC203.html rename to ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC34.html b/ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc similarity index 100% rename from python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC34.html rename to ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC4.html b/ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc similarity index 100% rename from python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC4.html rename to ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc diff --git a/ecocode-rules-specifications/src/main/rules/EC404/EC404.json b/ecocode-rules-specifications/src/main/rules/EC404/EC404.json new file mode 100644 index 000000000..c04d919d3 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC404/EC404.json @@ -0,0 +1,15 @@ +{ + "title": "Use generator comprehension instead of list comprehension in for loop declaration", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "15min" + }, + "tags": [ + "performance", + "eco-design", + "ecocode" + ], + "defaultSeverity": "Minor" +} diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC404.html b/ecocode-rules-specifications/src/main/rules/EC404/python/EC404.asciidoc similarity index 100% rename from python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC404.html rename to ecocode-rules-specifications/src/main/rules/EC404/python/EC404.asciidoc diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC66.html b/ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc similarity index 100% rename from python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC66.html rename to ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC69.html b/ecocode-rules-specifications/src/main/rules/EC69/python/EC69.asciidoc similarity index 100% rename from python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC69.html rename to ecocode-rules-specifications/src/main/rules/EC69/python/EC69.asciidoc diff --git a/ecocode-rules-specifications/src/main/rules/EC7/EC7.json b/ecocode-rules-specifications/src/main/rules/EC7/EC7.json new file mode 100644 index 000000000..46c194d56 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC7/EC7.json @@ -0,0 +1,15 @@ +{ + "title": "Avoid creating getter and setter methods in classes", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "eco-design", + "performance", + "ecocode" + ], + "defaultSeverity": "Minor" +} diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC7.html b/ecocode-rules-specifications/src/main/rules/EC7/python/EC7.asciidoc similarity index 100% rename from python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC7.html rename to ecocode-rules-specifications/src/main/rules/EC7/python/EC7.asciidoc diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC72.html b/ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc similarity index 100% rename from python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC72.html rename to ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc diff --git a/python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC74.html b/ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc similarity index 100% rename from python-plugin/src/main/resources/fr/greencodeinitiative/l10n/python/rules/python/EC74.html rename to ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index 3447d148a..b2a7d6e60 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -16,16 +16,24 @@ https://github.com/green-code-initiative/ecoCode/tree/main/python-plugin + + ${project.groupId} + ecocode-rules-specifications + ${project.version} + python + org.sonarsource.python sonar-python-plugin sonar-plugin + provided org.sonarsource.sonarqube sonar-plugin-api + provided @@ -63,6 +71,11 @@ ${java.version} + + + org.apache.maven.plugins + maven-shade-plugin + org.apache.maven.plugins maven-dependency-plugin diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java index 2718b28f0..23ff4f51e 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java @@ -17,58 +17,32 @@ package fr.greencodeinitiative.python; import fr.greencodeinitiative.python.checks.*; -import org.sonar.api.rules.RuleType; +import org.sonar.api.SonarRuntime; import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.api.server.rule.RulesDefinitionAnnotationLoader; import org.sonar.plugins.python.api.PythonCustomRuleRepository; +import org.sonarsource.analyzer.commons.RuleMetadataLoader; -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; public class PythonRuleRepository implements RulesDefinition, PythonCustomRuleRepository { public static final String LANGUAGE = "py"; public static final String NAME = "ecoCode"; - public static final String RESOURCE_BASE_PATH = "/fr/greencodeinitiative/l10n/python/rules/python/"; + public static final String RESOURCE_BASE_PATH = "io/ecocode/rules/python"; public static final String REPOSITORY_KEY = "ecocode-python"; - @Override - public void define(Context context) { - NewRepository repository = context.createRepository(repositoryKey(), LANGUAGE).setName(NAME); - - new RulesDefinitionAnnotationLoader().load(repository, checkClasses().toArray(new Class[] {})); - - // technical debt - Map remediationCosts = new HashMap<>(); - remediationCosts.put(AvoidSQLRequestInLoop.RULE_KEY, "10min"); - remediationCosts.put(AvoidFullSQLRequest.RULE_KEY, "20min"); - repository.rules().forEach(rule -> { - rule.setType(RuleType.CODE_SMELL); - String debt = remediationCosts.get(rule.key()); - - // TODO DDC : create support to use org.apache.commons.lang.StringUtils -// if (StringUtils.isBlank(debt)) { - if (debt == null || debt.trim().equals("")) { - // default debt to 5min for issue correction - rule.setDebtRemediationFunction( - rule.debtRemediationFunctions().constantPerIssue("5min")); - } else { - rule.setDebtRemediationFunction( - rule.debtRemediationFunctions().constantPerIssue(debt)); - } - }); + private final SonarRuntime sonarRuntime; - // HTML description - repository.rules().forEach(rule -> - rule.setHtmlDescription(loadResource(RESOURCE_BASE_PATH + rule.key() + ".html"))); + public PythonRuleRepository(SonarRuntime sonarRuntime) { + this.sonarRuntime = sonarRuntime; + } + @Override + public void define(Context context) { + NewRepository repository = context.createRepository(REPOSITORY_KEY, LANGUAGE).setName(NAME); + RuleMetadataLoader ruleMetadataLoader = new RuleMetadataLoader(RESOURCE_BASE_PATH, sonarRuntime); + ruleMetadataLoader.addRulesByAnnotatedClass(repository, (List) checkClasses()); repository.done(); } @@ -92,21 +66,4 @@ public List checkClasses() { DetectUnoptimizedImageFormat.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); - } - } } diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java index 477f5d4bb..e270ad449 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java @@ -16,20 +16,26 @@ */ package fr.greencodeinitiative.python; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.sonar.api.Plugin; import org.sonar.api.SonarRuntime; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; -public class PythonPluginTest { +class PythonPluginTest { + private Plugin.Context context; - @Test - public void test() { + @BeforeEach + void init() { SonarRuntime sonarRuntime = mock(SonarRuntime.class); - Plugin.Context context = new Plugin.Context(sonarRuntime); + context = new Plugin.Context(sonarRuntime); new PythonPlugin().define(context); + } + + @Test + void test() { assertThat(context.getExtensions()).hasSize(1); } diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java index 828447a4d..714ef278e 100644 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java +++ b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java @@ -16,45 +16,88 @@ */ package fr.greencodeinitiative.python; -import static org.assertj.core.api.Assertions.assertThat; - import org.assertj.core.api.SoftAssertions; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.sonar.api.SonarRuntime; import org.sonar.api.server.rule.RulesDefinition; +import org.sonar.api.utils.Version; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; -public class PythonRuleRepositoryTest { +class PythonRuleRepositoryTest { - private PythonRuleRepository pythonRuleRepository; - private RulesDefinition.Context context; private RulesDefinition.Repository repository; - @Before - public void init() { - pythonRuleRepository = new PythonRuleRepository(); - context = new RulesDefinition.Context(); - pythonRuleRepository.define(context); - repository = context.repository(PythonRuleRepository.REPOSITORY_KEY); + @BeforeEach + void init() { + // TODO: Remove this check after Git repo split + /* + On an IDE (like IntelliJ), if the developer runs the unit tests without building/generating the Maven goals on the + "ecocode-rules-specifications" module before, the unit tests will not see the generated HTML descriptions (from ASCIIDOC files). + The developer must therefore configure his IDE to build the `ecocode-rules-specifications` module before launching the Tests. + + When the `python-plugin` submodule is in a specific Git repository, `ecocode-rules-specifications` will be fetched from a classic + external Maven dependency. There will therefore no longer be any need to perform this specific configuration. + */ + if (PythonRuleRepository.class.getResource("/io/ecocode/rules/python/EC4.json") == null) { + String message = "'ecocode-rules-specification' resources corrupted. Please check build of 'ecocode-rules-specification' module"; + if (System.getProperties().keySet().stream().anyMatch(k -> k.toString().startsWith("idea."))) { + message += "\n\nOn 'IntelliJ IDEA':" + + "\n1. go to settings :" + + "\n > Build, Execution, Deployment > Build Tools > Maven > Runner" + + "\n2. check option:" + + "\n > Delegate IDE build/run actions to Maven" + + "\n3. Click on menu: " + + "\n > Build > Build Project" + ; + } + fail(message); + } + + final SonarRuntime sonarRuntime = mock(SonarRuntime.class); + doReturn(Version.create(0, 0)).when(sonarRuntime).getApiVersion(); + PythonRuleRepository rulesDefinition = new PythonRuleRepository(sonarRuntime); + RulesDefinition.Context context = new RulesDefinition.Context(); + rulesDefinition.define(context); + repository = context.repository(rulesDefinition.repositoryKey()); } @Test - public void test() { - assertThat(pythonRuleRepository.repositoryKey()).isEqualTo(PythonRuleRepository.REPOSITORY_KEY); - assertThat(context.repositories()).hasSize(1).extracting("key").containsExactly(pythonRuleRepository.repositoryKey()); - assertThat(context.repositories().get(0).rules()).hasSize(10); - assertThat(pythonRuleRepository.checkClasses()).hasSize(10); + @DisplayName("Test repository metadata") + void testMetadata() { + assertThat(repository.name()).isEqualTo("ecoCode"); + assertThat(repository.language()).isEqualTo("py"); + assertThat(repository.key()).isEqualTo("ecocode-python"); } + @Test + void testRegistredRules() { + assertThat(repository.rules()).hasSize(10); + } - /** - * Check all rule keys must be prefixed by 'EC' - */ @Test - public void testRuleKeyPrefix() { + @DisplayName("All rule keys must be prefixed by 'EC'") + void testRuleKeyPrefix() { SoftAssertions assertions = new SoftAssertions(); repository.rules().forEach( rule -> assertions.assertThat(rule.key()).startsWith("EC") ); assertions.assertAll(); } + + @Test + void testAllRuleParametersHaveDescription() { + SoftAssertions assertions = new SoftAssertions(); + repository.rules().stream() + .flatMap(rule -> rule.params().stream()) + .forEach(param -> assertions.assertThat(param.description()) + .as("description for " + param.key()) + .isNotEmpty()); + assertions.assertAll(); + } } From 837c2bf4a16aa497ac5dc4e79be37ee274d381bb Mon Sep 17 00:00:00 2001 From: jycr Date: Tue, 27 Jun 2023 09:21:54 +0200 Subject: [PATCH 110/170] green-code-initiative/ecoCode#92 improves code quality (reduce code duplication) --- .../src/main/rules/EC3/EC3.json | 1 + .../src/main/rules/EC34/EC34.json | 2 +- .../src/main/rules/EC66/EC66.json | 1 + .../java/checks/ArrayCopyCheck.java | 7 +------ .../java/checks/AvoidConcatenateStringsInLoop.java | 9 +-------- .../java/checks/AvoidFullSQLRequest.java | 9 ++------- .../java/checks/AvoidGettingSizeCollectionInLoop.java | 7 +------ .../java/checks/AvoidMultipleIfElseStatement.java | 7 +------ .../java/checks/AvoidRegexPatternNotStatic.java | 8 +------- .../java/checks/AvoidSQLRequestInLoop.java | 4 +--- .../java/checks/AvoidSetConstantInBatchUpdate.java | 7 ++----- .../checks/AvoidSpringRepositoryCallInLoopCheck.java | 7 +------ .../java/checks/AvoidStatementForDMLQueries.java | 2 +- .../java/checks/AvoidUsageOfStaticCollections.java | 8 +------- .../java/checks/AvoidUsingGlobalVariablesCheck.java | 8 +------- .../checks/FreeResourcesOfAutoCloseableInterface.java | 8 +------- .../java/checks/IncrementCheck.java | 8 +------- .../checks/InitializeBufferWithAppropriateSize.java | 8 +------- .../checks/NoFunctionCallWhenDeclaringForLoop.java | 4 +--- .../java/checks/OptimizeReadFileExceptions.java | 8 +------- .../checks/UnnecessarilyAssignValuesToVariables.java | 4 +--- .../java/checks/UseCorrectForLoop.java | 8 +------- .../php/checks/AvoidDoubleQuoteCheck.java | 9 +-------- .../php/checks/AvoidFullSQLRequestCheck.java | 10 +--------- .../checks/AvoidGettingSizeCollectionInLoopCheck.java | 10 +--------- .../php/checks/AvoidSQLRequestInLoopCheck.java | 9 +-------- ...TryCatchFinallyCheck_NOK_failsAllTryStatements.java | 9 +-------- .../php/checks/AvoidUsingGlobalVariablesCheck.java | 9 +-------- .../greencodeinitiative/php/checks/IncrementCheck.java | 9 +-------- .../php/checks/NoFunctionCallWhenDeclaringForLoop.java | 9 +-------- .../php/checks/UseOfMethodsForBasicOperations.java | 9 +-------- .../python/checks/AvoidDoubleQuoteCheck.java | 9 +-------- .../python/checks/AvoidFullSQLRequest.java | 10 +--------- .../python/checks/AvoidGettersAndSetters.java | 9 +-------- .../checks/AvoidGlobalVariableInFunctionCheck.java | 9 +-------- .../checks/AvoidListComprehensionInIterations.java | 9 +-------- .../python/checks/AvoidSQLRequestInLoop.java | 10 +--------- .../python/checks/AvoidTryCatchFinallyCheck.java | 9 +-------- .../checks/AvoidUnoptimizedVectorImagesCheck.java | 9 +-------- .../python/checks/DetectUnoptimizedImageFormat.java | 8 +------- .../checks/NoFunctionCallWhenDeclaringForLoop.java | 9 +-------- 41 files changed, 43 insertions(+), 266 deletions(-) diff --git a/ecocode-rules-specifications/src/main/rules/EC3/EC3.json b/ecocode-rules-specifications/src/main/rules/EC3/EC3.json index f511c1c2a..33916b15e 100644 --- a/ecocode-rules-specifications/src/main/rules/EC3/EC3.json +++ b/ecocode-rules-specifications/src/main/rules/EC3/EC3.json @@ -7,6 +7,7 @@ "constantCost": "5min" }, "tags": [ + "bad-practice", "eco-design", "performance", "ecocode" diff --git a/ecocode-rules-specifications/src/main/rules/EC34/EC34.json b/ecocode-rules-specifications/src/main/rules/EC34/EC34.json index 4191cbb71..00bc65320 100644 --- a/ecocode-rules-specifications/src/main/rules/EC34/EC34.json +++ b/ecocode-rules-specifications/src/main/rules/EC34/EC34.json @@ -1,5 +1,5 @@ { - "title": "Avoid using try-catch-finally statement", + "title": "Avoid using try-catch statement", "type": "CODE_SMELL", "status": "ready", "remediation": { diff --git a/ecocode-rules-specifications/src/main/rules/EC66/EC66.json b/ecocode-rules-specifications/src/main/rules/EC66/EC66.json index 6ed6137dc..034168254 100644 --- a/ecocode-rules-specifications/src/main/rules/EC66/EC66.json +++ b/ecocode-rules-specifications/src/main/rules/EC66/EC66.json @@ -7,6 +7,7 @@ "constantCost": "5min" }, "tags": [ + "bad-practice", "eco-design", "performance", "ecocode" diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java index 5abd5201e..080fc83d1 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java @@ -6,7 +6,6 @@ import java.util.function.Predicate; import java.util.stream.Collectors; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.ArrayAccessExpressionTree; @@ -37,11 +36,7 @@ * @author Aubay * @formatter:off */ -@Rule(key = "EC27", - name = "Developpement", - description = ArrayCopyCheck.MESSAGERULE, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC27") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GRPS0027") public class ArrayCopyCheck extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java index 996043b5a..90d68b852 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java @@ -2,10 +2,8 @@ import java.util.Arrays; import java.util.List; - import javax.annotation.Nonnull; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; @@ -15,12 +13,7 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = "EC75", - name = "Developpement", - description = AvoidConcatenateStringsInLoop.MESSAGE_RULE, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode", "memory"}) +@Rule(key = "EC75") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S75") public class AvoidConcatenateStringsInLoop extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java index 3d9bcc22f..e8dd5d28b 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java @@ -6,7 +6,7 @@ import static java.util.Collections.singletonList; import static java.util.regex.Pattern.CASE_INSENSITIVE; import static java.util.regex.Pattern.compile; -import org.sonar.check.Priority; + import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.LiteralTree; @@ -14,12 +14,7 @@ import org.sonar.plugins.java.api.tree.Tree.Kind; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = "EC74", - name = "Developpement", - description = AvoidFullSQLRequest.MESSAGERULE, - priority = Priority.MINOR, - tags = {"performance", "sql", "eco-design", "ecocode", "network"}) +@Rule(key = "EC74") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S74") public class AvoidFullSQLRequest extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java index 9f70e0ede..7112bb685 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java @@ -5,7 +5,6 @@ import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.semantic.MethodMatchers; @@ -18,11 +17,7 @@ import org.sonar.plugins.java.api.tree.WhileStatementTree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC3", - name = "Developpement", - description = AvoidGettingSizeCollectionInLoop.MESSAGERULE, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC3") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GSCIL") public class AvoidGettingSizeCollectionInLoop extends IssuableSubscriptionVisitor { protected static final String MESSAGERULE = "Avoid getting the size of the collection in the loop"; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java index 64a8fa037..9460642ab 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java @@ -3,7 +3,6 @@ import java.util.Arrays; import java.util.List; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.BlockTree; @@ -12,11 +11,7 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC2", - name = "Developpement", - description = AvoidMultipleIfElseStatement.RULE_MESSAGE, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC2") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "AMIES") public class AvoidMultipleIfElseStatement extends IssuableSubscriptionVisitor { protected static final String RULE_MESSAGE = "Using a switch statement instead of multiple if-else if possible"; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java index 4b6949cce..a4e8e2f7e 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java @@ -6,7 +6,6 @@ import javax.annotation.Nonnull; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.semantic.MethodMatchers; @@ -16,12 +15,7 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = "EC77", - name = "Developpement", - description = AvoidRegexPatternNotStatic.MESSAGE_RULE, - priority = Priority.MINOR, - tags = {"performance", "regex", "eco-design", "ecocode", "memory"}) +@Rule(key = "EC77") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S77") public class AvoidRegexPatternNotStatic extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java index 532b89c12..297895e08 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java @@ -3,7 +3,6 @@ import java.util.Arrays; import java.util.List; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.semantic.MethodMatchers; @@ -14,8 +13,7 @@ import org.sonar.plugins.java.api.tree.Tree.Kind; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC72", name = "Developpement", description = AvoidSQLRequestInLoop.MESSAGERULE, priority = Priority.MINOR, - tags = {"performance", "sql", "spring", "eco-design", "ecocode", "memory", "network"}) +@Rule(key = "EC72") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S72") public class AvoidSQLRequestInLoop extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java index 9a692f82d..4a014c2a3 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java @@ -6,7 +6,7 @@ import static fr.greencodeinitiative.java.checks.ConstOrLiteralDeclare.isLiteral; import static java.util.Arrays.asList; -import org.sonar.check.Priority; + import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.semantic.MethodMatchers; @@ -21,10 +21,7 @@ import static org.sonar.plugins.java.api.tree.Tree.Kind.MEMBER_SELECT; import static org.sonar.plugins.java.api.tree.Tree.Kind.METHOD_INVOCATION; -@Rule(key = "EC78", name = "Developpement", - description = AvoidSetConstantInBatchUpdate.MESSAGERULE, - priority = Priority.MINOR, - tags = {"eco-design", "ecocode", "sql", "performance", "memory"}) +@Rule(key = "EC78") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S78") public class AvoidSetConstantInBatchUpdate extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java index 5730b69d9..6cf843392 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java @@ -3,7 +3,6 @@ import java.util.Arrays; import java.util.List; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.semantic.MethodMatchers; @@ -12,11 +11,7 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC1", - name = "Developpement", - description = AvoidSpringRepositoryCallInLoopCheck.RULE_MESSAGE, - priority = Priority.MINOR, - tags = {"performance", "spring", "eco-design", "ecocode"}) +@Rule(key = "EC1") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GRC1") public class AvoidSpringRepositoryCallInLoopCheck extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java index efd76ca31..f273ae707 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java @@ -14,7 +14,7 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC5", tags={"performance", "sql", "eco-design", "ecocode"}) +@Rule(key = "EC5") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "SDMLQ1") public class AvoidStatementForDMLQueries extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java index d4de0d49e..c6eba94b7 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java @@ -6,7 +6,6 @@ import javax.annotation.Nonnull; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.BaseTreeVisitor; @@ -14,12 +13,7 @@ import org.sonar.plugins.java.api.tree.VariableTree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = "EC76", - name = "Developpement", - description = AvoidUsageOfStaticCollections.MESSAGE_RULE, - priority = Priority.MINOR, - tags = {"cwe", "leak", "eco-design", "ecocode", "memory"}) +@Rule(key = "EC76") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S76") public class AvoidUsageOfStaticCollections extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java index e2f08c522..bdc4dee1b 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java @@ -4,7 +4,6 @@ import java.util.List; import com.google.re2j.Pattern; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.Tree; @@ -12,12 +11,7 @@ import org.sonar.plugins.java.api.tree.VariableTree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = "EC4", - name = "Developpement", - description = "

      Prefer local variables to globals

      ", - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC4") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "D4") public class AvoidUsingGlobalVariablesCheck extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java index 0cacf32d0..fb41ba0f7 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java @@ -8,7 +8,6 @@ import javax.annotation.ParametersAreNonnullByDefault; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.JavaFileScannerContext; @@ -19,12 +18,7 @@ import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = "EC79", - name = "Developpement", - description = FreeResourcesOfAutoCloseableInterface.MESSAGE_RULE, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC79") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S79") public class FreeResourcesOfAutoCloseableInterface extends IssuableSubscriptionVisitor { private final Deque withinTry = new LinkedList<>(); diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java index 1ac657aa3..7b480b1c7 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java @@ -3,19 +3,13 @@ import java.util.Collections; import java.util.List; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.Tree; import org.sonar.plugins.java.api.tree.Tree.Kind; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = "EC67", - name = "Developpement", - description = IncrementCheck.MESSAGERULE, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC67") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S67") public class IncrementCheck extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java index 0090a7ac5..bb3cc4dd6 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java @@ -3,7 +3,6 @@ import java.util.Collections; import java.util.List; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.NewClassTree; @@ -11,12 +10,7 @@ import org.sonar.plugins.java.api.tree.Tree.Kind; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = "EC32", - name = "Developpement", - description = InitializeBufferWithAppropriateSize.RULE_MESSAGE, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC32") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GRSP0032") public class InitializeBufferWithAppropriateSize extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java index 6c8758aa0..1c7c47347 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java @@ -7,7 +7,6 @@ import java.util.List; import java.util.Map; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.BaseTreeVisitor; @@ -21,8 +20,7 @@ import org.sonar.plugins.java.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule(key = "EC69", name = "Developpement", description = NoFunctionCallWhenDeclaringForLoop.MESSAGERULE, priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC69") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S69") public class NoFunctionCallWhenDeclaringForLoop extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java index 0ee8a79c7..9766d2009 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java @@ -6,7 +6,6 @@ import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.CatchTree; @@ -16,12 +15,7 @@ import org.sonar.plugins.java.api.tree.TryStatementTree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = "EC28", - name = "Developpement", - description = OptimizeReadFileExceptions.MESSAGERULE, - priority = Priority.MINOR, - tags = {"performance", "error-handling", "eco-design", "ecocode"}) +@Rule(key = "EC28") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "GRSP0028") public class OptimizeReadFileExceptions extends IssuableSubscriptionVisitor { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java index d8a7e69da..8c6dde8f0 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java @@ -1,6 +1,5 @@ package fr.greencodeinitiative.java.checks; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.JavaFileScanner; import org.sonar.plugins.java.api.JavaFileScannerContext; @@ -11,8 +10,7 @@ import javax.annotation.CheckForNull; import java.util.*; -@Rule(key = "EC63", name = "Developpement", description = "Do not unnecessarily assign values to variables", priority = Priority.MINOR, - tags = {"eco-design", "ecocode", "memory"}) +@Rule(key = "EC63") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S63") public class UnnecessarilyAssignValuesToVariables extends BaseTreeVisitor implements JavaFileScanner { diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java index 5cbc68e2f..6da7c13c1 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java @@ -3,7 +3,6 @@ import java.util.Arrays; import java.util.List; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.ForEachStatement; @@ -11,12 +10,7 @@ import org.sonar.plugins.java.api.tree.Tree.Kind; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = "EC53", - name = "Developpement", - description = UseCorrectForLoop.MESSAGERULE, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC53") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S53") public class UseCorrectForLoop extends IssuableSubscriptionVisitor { diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheck.java index cc89b1600..67e6a7c47 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheck.java @@ -7,23 +7,16 @@ import java.util.List; import java.util.Map; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.php.api.tree.Tree; import org.sonar.plugins.php.api.tree.expression.LiteralTree; import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = AvoidDoubleQuoteCheck.RULE_KEY, - name = AvoidDoubleQuoteCheck.ERROR_MESSAGE, - description = AvoidDoubleQuoteCheck.ERROR_MESSAGE, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC66") @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S66") public class AvoidDoubleQuoteCheck extends PHPSubscriptionCheck { - public static final String RULE_KEY = "EC66"; public static final String ERROR_MESSAGE = "Avoid using double quote (\"), prefer using simple quote (')"; private static final Map> linesWithIssuesByFile = new HashMap<>(); diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheck.java index c6fe2b28a..61c175d36 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheck.java @@ -4,7 +4,6 @@ import java.util.List; import java.util.regex.Pattern; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.php.api.tree.Tree; import org.sonar.plugins.php.api.tree.Tree.Kind; @@ -12,17 +11,10 @@ import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = AvoidFullSQLRequestCheck.RULE_KEY, - name = AvoidFullSQLRequestCheck.ERROR_MESSAGE, - description = AvoidFullSQLRequestCheck.ERROR_MESSAGE, - priority = Priority.MINOR, - tags = {"sql", "performance", "eco-design", "ecocode"}) +@Rule(key = "EC74") @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S74") public class AvoidFullSQLRequestCheck extends PHPSubscriptionCheck { - public static final String RULE_KEY = "EC74"; - public static final String ERROR_MESSAGE = "Don't use the query SELECT * FROM"; private static final Pattern PATTERN = Pattern.compile("(?i).*select.*\\*.*from.*"); diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopCheck.java index 7ef27ade9..de7fd1729 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopCheck.java @@ -1,6 +1,5 @@ package fr.greencodeinitiative.php.checks; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.php.api.tree.SeparatedList; import org.sonar.plugins.php.api.tree.Tree; @@ -16,16 +15,9 @@ import java.util.List; import java.util.regex.Pattern; -@Rule( - key = AvoidGettingSizeCollectionInLoopCheck.RULE_KEY, - name = AvoidGettingSizeCollectionInLoopCheck.ERROR_MESSAGE, - description = AvoidGettingSizeCollectionInLoopCheck.ERROR_MESSAGE, - priority = Priority.MINOR, - tags = {"eco-design", "ecocode", "bad-practice", "performance"} -) +@Rule(key = "EC3") public class AvoidGettingSizeCollectionInLoopCheck extends PHPSubscriptionCheck { - public static final String RULE_KEY = "EC3"; public static final String ERROR_MESSAGE = "Avoid getting the size of the collection in the loop"; private static final Pattern PATTERN = Pattern.compile("\\b(?:count|sizeof|iterator_count)\\b"); diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheck.java index 8a392fcb3..0badb8c2b 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheck.java @@ -4,7 +4,6 @@ import java.util.List; import java.util.regex.Pattern; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.php.api.tree.Tree; import org.sonar.plugins.php.api.tree.Tree.Kind; @@ -18,16 +17,10 @@ import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = AvoidSQLRequestInLoopCheck.RULE_KEY, - name = AvoidSQLRequestInLoopCheck.ERROR_MESSAGE, - description = AvoidSQLRequestInLoopCheck.ERROR_MESSAGE, - priority = Priority.MINOR, - tags = {"sql", "performance", "eco-design", "ecocode"}) +@Rule(key = "EC72") @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S72") public class AvoidSQLRequestInLoopCheck extends PHPSubscriptionCheck { - public static final String RULE_KEY = "EC72"; public static final String ERROR_MESSAGE = "Avoid SQL request in loop"; private static final Pattern PATTERN = Pattern.compile("(mysql(i::|_)query\\s*\\(.*)|(oci_execute\\(.*)"); diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.java index fa818f8c5..6aa9943a7 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.java @@ -3,22 +3,15 @@ import java.util.Collections; import java.util.List; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.php.api.tree.Tree; import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.RULE_KEY, - name = AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.ERROR_MESSAGE, - description = AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.ERROR_MESSAGE, - priority = Priority.MINOR, - tags = {"error-handling", "performance", "eco-design", "ecocode"}) +@Rule(key = "EC34") @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S34") public class AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements extends PHPSubscriptionCheck { - public static final String RULE_KEY = "EC34"; public static final String ERROR_MESSAGE = "Avoid using try-catch"; @Override diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheck.java index 7eecfdb2a..1b37a96e5 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheck.java @@ -2,22 +2,15 @@ import java.util.regex.Pattern; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.php.api.tree.declaration.FunctionDeclarationTree; import org.sonar.plugins.php.api.visitors.PHPVisitorCheck; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = AvoidUsingGlobalVariablesCheck.RULE_KEY, - name = AvoidUsingGlobalVariablesCheck.ERROR_MESSAGE, - description = AvoidUsingGlobalVariablesCheck.ERROR_MESSAGE, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC4") @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "D4") public class AvoidUsingGlobalVariablesCheck extends PHPVisitorCheck { - public static final String RULE_KEY = "EC4"; public static final String ERROR_MESSAGE = "Prefer local variables to globals"; private static final Pattern PATTERN = Pattern.compile("^.*(global \\$|\\$GLOBALS).*$", Pattern.CASE_INSENSITIVE); diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java index 79bd2cb4a..904cd404b 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java @@ -3,23 +3,16 @@ import java.util.Collections; import java.util.List; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.php.api.tree.Tree; import org.sonar.plugins.php.api.tree.Tree.Kind; import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = IncrementCheck.RULE_KEY, - name = IncrementCheck.ERROR_MESSAGE, - description = IncrementCheck.ERROR_MESSAGE, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC67") @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S67") public class IncrementCheck extends PHPSubscriptionCheck { - public static final String RULE_KEY = "EC67"; public static final String ERROR_MESSAGE = "Remove the usage of $i++. prefer ++$i"; @Override diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoop.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoop.java index 39ddca9a4..999d0cfe5 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoop.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoop.java @@ -3,7 +3,6 @@ import java.util.Collections; import java.util.List; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.php.api.tree.SeparatedList; import org.sonar.plugins.php.api.tree.Tree; @@ -14,16 +13,10 @@ import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = NoFunctionCallWhenDeclaringForLoop.RULE_KEY, - name = NoFunctionCallWhenDeclaringForLoop.ERROR_MESSAGE, - description = NoFunctionCallWhenDeclaringForLoop.ERROR_MESSAGE, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC69") @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S69") public class NoFunctionCallWhenDeclaringForLoop extends PHPSubscriptionCheck { - public static final String RULE_KEY = "EC69"; public static final String ERROR_MESSAGE = "Do not call a function in for-type loop declaration"; @Override diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperations.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperations.java index a1d03d769..1285fb4d7 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperations.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperations.java @@ -6,7 +6,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.php.api.tree.ScriptTree; import org.sonar.plugins.php.api.tree.Tree; @@ -18,16 +17,10 @@ import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = UseOfMethodsForBasicOperations.RULE_KEY, - name = UseOfMethodsForBasicOperations.ERROR_MESSAGE, - description = UseOfMethodsForBasicOperations.ERROR_MESSAGE, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC22") @DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "D2") public class UseOfMethodsForBasicOperations extends PHPSubscriptionCheck { - public static final String RULE_KEY = "EC22"; protected static final String ERROR_MESSAGE = "Use of methods for basic operations"; @Override diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java index 033c468d1..e6b191289 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java @@ -1,20 +1,13 @@ package fr.greencodeinitiative.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.SubscriptionContext; import org.sonar.plugins.python.api.tree.StringLiteral; import org.sonar.plugins.python.api.tree.Tree; -@Rule( - key = AvoidDoubleQuoteCheck.RULE_KEY, - name = AvoidDoubleQuoteCheck.MESSAGE_RULE, - description = AvoidDoubleQuoteCheck.MESSAGE_RULE, - priority = Priority.MINOR, - tags = {"eco-design", "ecocode", "bad-practice"}) +@Rule(key = "EC66") public class AvoidDoubleQuoteCheck extends PythonSubscriptionCheck { - public static final String RULE_KEY = "EC66"; public static final String MESSAGE_RULE = "Avoid using quotation mark (\"), prefer using simple quote (')"; @Override public void initialize(Context context) { diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java index 77c5f43be..8c6d4eedf 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java @@ -7,7 +7,6 @@ import java.util.Map; import java.util.regex.Pattern; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.python.api.PythonSubscriptionCheck; import org.sonar.plugins.python.api.SubscriptionContext; @@ -16,17 +15,10 @@ import org.sonar.plugins.python.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = AvoidFullSQLRequest.RULE_KEY, - name = AvoidFullSQLRequest.MESSAGERULE, - description = AvoidFullSQLRequest.MESSAGERULE, - priority = Priority.MINOR, - tags = {"sql", "performance", "eco-design", "ecocode"}) +@Rule(key = "EC74") @DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "S74") public class AvoidFullSQLRequest extends PythonSubscriptionCheck { - public static final String RULE_KEY = "EC74"; - protected static final String MESSAGERULE = "Don't use the query SELECT * FROM"; // TODO DDC : create support to add in deployment th dependency com.google.re2j:re2j diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSetters.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSetters.java index fc1dddca4..beb063de7 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSetters.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSetters.java @@ -3,7 +3,6 @@ import java.util.List; import java.util.stream.Collectors; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.python.api.PythonSubscriptionCheck; import org.sonar.plugins.python.api.SubscriptionContext; @@ -18,16 +17,10 @@ import org.sonar.plugins.python.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = AvoidGettersAndSetters.RULE_KEY, - name = AvoidGettersAndSetters.DESCRIPTION, - description = AvoidGettersAndSetters.DESCRIPTION, - priority = Priority.MINOR, - tags = {"convention", "eco-design", "ecocode"}) +@Rule(key = "EC7") @DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "D7") public class AvoidGettersAndSetters extends PythonSubscriptionCheck { - public static final String RULE_KEY = "EC7"; public static final String DESCRIPTION = "Avoid creating getter and setter methods in classes"; @Override diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheck.java index ab4302bbd..82bc46b74 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheck.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheck.java @@ -5,7 +5,6 @@ import java.util.List; import java.util.Map; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.python.api.PythonSubscriptionCheck; import org.sonar.plugins.python.api.SubscriptionCheck; @@ -62,16 +61,10 @@ import org.sonar.plugins.python.api.tree.YieldStatement; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = AvoidGlobalVariableInFunctionCheck.RULE_KEY, - name = "Do not call global variables directly inside functions", - description = AvoidGlobalVariableInFunctionCheck.DESCRIPTION, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC4") @DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "D4") public class AvoidGlobalVariableInFunctionCheck extends PythonSubscriptionCheck { - public static final String RULE_KEY = "EC4"; public static final String DESCRIPTION = "Use local variable (function/class scope) instead of global variable (application scope)"; private List globalVariables; diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java index 5cb64346d..917d053c9 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java @@ -1,6 +1,5 @@ package fr.greencodeinitiative.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.SubscriptionContext; @@ -18,15 +17,9 @@ import static org.sonar.plugins.python.api.tree.Tree.Kind.LIST_COMPREHENSION; import static org.sonar.plugins.python.api.tree.Tree.Kind.REGULAR_ARGUMENT; -@Rule( - key = AvoidListComprehensionInIterations.RULE_KEY, - name = AvoidListComprehensionInIterations.DESCRIPTION, - description = AvoidListComprehensionInIterations.DESCRIPTION, - priority = Priority.MINOR, - tags = {"eco-design", "ecocode", "performance"}) +@Rule(key = "EC404") public class AvoidListComprehensionInIterations extends PythonSubscriptionCheck { - public static final String RULE_KEY = "EC404"; public static final String DESCRIPTION = "Use generator comprehension instead of list comprehension in for loop declaration"; @Override diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoop.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoop.java index 7a7c1187e..a2bb20786 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoop.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoop.java @@ -6,7 +6,6 @@ import java.util.Objects; import java.util.Set; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.python.api.PythonSubscriptionCheck; import org.sonar.plugins.python.api.SubscriptionContext; @@ -20,17 +19,10 @@ import org.sonar.plugins.python.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = AvoidSQLRequestInLoop.RULE_KEY, - name = "Avoid SQL request in loop", - description = AvoidSQLRequestInLoop.MESSAGE_RULE, - priority = Priority.MINOR, - tags = {"sql", "performance", "eco-design", "ecocode"}) +@Rule(key = "EC72") @DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "S72") public class AvoidSQLRequestInLoop extends PythonSubscriptionCheck { - public static final String RULE_KEY = "EC72"; - // TODO: Handle ORM lib private static final List SQL_LIBS = Arrays.asList("cx_Oracle", "mysql.connector", "psycopg2", "pymssql", "pyodbc", "sqlite3"); diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java index 43ae16492..be801c44d 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java @@ -1,6 +1,5 @@ package fr.greencodeinitiative.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.SubscriptionContext; @@ -8,16 +7,10 @@ import org.sonar.plugins.python.api.tree.TryStatement; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = AvoidTryCatchFinallyCheck.RULE_KEY, - name = "Avoid using try-catch statement", - description = AvoidTryCatchFinallyCheck.DESCRIPTION, - priority = Priority.MINOR, - tags = {"error-handling", "performance", "eco-design", "ecocode"}) +@Rule(key = "EC34") @DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "S34") public class AvoidTryCatchFinallyCheck extends PythonSubscriptionCheck { - public static final String RULE_KEY = "EC34"; public static final String DESCRIPTION = "Avoid the use of try-catch"; @Override diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java index 5819eeec0..f3a9c3686 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java @@ -3,21 +3,14 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.python.api.PythonSubscriptionCheck; import org.sonar.plugins.python.api.SubscriptionContext; import org.sonar.plugins.python.api.tree.*; -@Rule( - key = AvoidUnoptimizedVectorImagesCheck.RULE_KEY, - name = AvoidUnoptimizedVectorImagesCheck.DESCRIPTION, - description = AvoidUnoptimizedVectorImagesCheck.DESCRIPTION, - priority = Priority.MINOR, - tags = {"eco-design", "ecocode"}) +@Rule(key = "EC10") public class AvoidUnoptimizedVectorImagesCheck extends PythonSubscriptionCheck { - public static final String RULE_KEY = "EC10"; public static final String DESCRIPTION = "Avoid using unoptimized vector images"; private static final Pattern LAYERS_PATTERN = Pattern.compile(""); diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java index 5cd3c48c7..a69599aed 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java @@ -1,6 +1,5 @@ package fr.greencodeinitiative.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.SubscriptionContext; @@ -10,12 +9,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -@Rule( - key = DetectUnoptimizedImageFormat.RULE_KEY, - name = DetectUnoptimizedImageFormat.MESSAGERULE, - description = DetectUnoptimizedImageFormat.MESSAGEERROR, - priority = Priority.MINOR, - tags = {"eco-design", "ecocode", "performance", "user-experience"}) +@Rule(key = "EC203") public class DetectUnoptimizedImageFormat extends PythonSubscriptionCheck { protected static final String RULE_KEY = "EC203"; diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoop.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoop.java index 5c7e09f05..b0bf30286 100644 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoop.java +++ b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoop.java @@ -1,22 +1,15 @@ package fr.greencodeinitiative.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.CallExpression; import org.sonar.plugins.python.api.tree.Tree; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; -@Rule( - key = NoFunctionCallWhenDeclaringForLoop.RULE_KEY, - name = NoFunctionCallWhenDeclaringForLoop.DESCRIPTION, - description = NoFunctionCallWhenDeclaringForLoop.DESCRIPTION, - priority = Priority.MINOR, - tags = {"performance", "eco-design", "ecocode"}) +@Rule(key = "EC69") @DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "S69") public class NoFunctionCallWhenDeclaringForLoop extends PythonSubscriptionCheck { - public static final String RULE_KEY = "EC69"; public static final String DESCRIPTION = "Do not call a function when declaring a for-type loop"; @Override From 9ab4abbcffc19701ef183e7632b3172e930e248e Mon Sep 17 00:00:00 2001 From: jycr Date: Fri, 14 Apr 2023 18:26:42 +0200 Subject: [PATCH 111/170] refactor: convert rule description from HTML to ASCIIDOC --- .../src/main/rules/EC1/java/EC1.asciidoc | 39 +- .../src/main/rules/EC10/python/EC10.asciidoc | 54 +-- .../src/main/rules/EC2/java/EC2.asciidoc | 53 +-- .../main/rules/EC203/python/EC203.asciidoc | 151 +++---- .../src/main/rules/EC22/php/EC22.asciidoc | 22 +- .../src/main/rules/EC27/java/EC27.asciidoc | 52 +-- .../src/main/rules/EC28/java/EC28.asciidoc | 57 +-- .../src/main/rules/EC3/java/EC3.asciidoc | 35 +- .../src/main/rules/EC3/php/EC3.asciidoc | 189 ++++---- .../src/main/rules/EC32/java/EC32.asciidoc | 40 +- .../src/main/rules/EC34/php/1GB.etsdiff.csv | 3 + .../src/main/rules/EC34/php/EC34.asciidoc | 114 ++--- .../src/main/rules/EC34/python/EC34.asciidoc | 22 +- .../src/main/rules/EC4/java/EC4.asciidoc | 71 +-- .../src/main/rules/EC4/php/EC4.asciidoc | 42 +- .../src/main/rules/EC4/python/EC4.asciidoc | 24 +- .../main/rules/EC404/python/EC404.asciidoc | 25 +- .../src/main/rules/EC5/java/EC5.asciidoc | 38 +- .../src/main/rules/EC53/java/EC53.asciidoc | 33 +- .../src/main/rules/EC63/java/EC63.asciidoc | 19 +- .../src/main/rules/EC66/php/1GB.etsdiff.csv | 3 + .../src/main/rules/EC66/php/EC66.asciidoc | 116 ++--- .../src/main/rules/EC66/python/EC66.asciidoc | 58 +-- .../src/main/rules/EC67/java/EC67.asciidoc | 18 +- .../src/main/rules/EC67/php/1GB.etsdiff.csv | 3 + .../src/main/rules/EC67/php/EC67.asciidoc | 112 ++--- .../src/main/rules/EC69/java/EC69.asciidoc | 39 +- .../src/main/rules/EC69/php/1GB.etsdiff.csv | 3 + .../src/main/rules/EC69/php/EC69.asciidoc | 110 +---- .../src/main/rules/EC69/python/EC69.asciidoc | 18 +- .../src/main/rules/EC7/python/EC7.asciidoc | 18 +- .../src/main/rules/EC72/java/EC72.asciidoc | 73 ++-- .../src/main/rules/EC72/php/1GB.etsdiff.csv | 3 + .../src/main/rules/EC72/php/2GB.etsdiff.csv | 3 + .../src/main/rules/EC72/php/4GB.etsdiff.csv | 3 + .../src/main/rules/EC72/php/8GB.etsdiff.csv | 3 + .../src/main/rules/EC72/php/EC72.asciidoc | 408 ++++-------------- .../src/main/rules/EC72/python/EC72.asciidoc | 40 +- .../src/main/rules/EC74/java/EC74.asciidoc | 34 +- .../src/main/rules/EC74/php/1GB.etsdiff.csv | 3 + .../src/main/rules/EC74/php/EC74.asciidoc | 129 ++---- .../src/main/rules/EC74/python/EC74.asciidoc | 34 +- .../src/main/rules/EC75/java/EC75.asciidoc | 57 ++- .../src/main/rules/EC76/java/EC76.asciidoc | 62 ++- .../src/main/rules/EC77/java/EC77.asciidoc | 88 ++-- .../src/main/rules/EC78/java/EC78.asciidoc | 60 +-- .../src/main/rules/EC79/java/EC79.asciidoc | 40 +- .../main/rules/etsdiff-methodology.asciidoc | 11 + 48 files changed, 1075 insertions(+), 1557 deletions(-) create mode 100644 ecocode-rules-specifications/src/main/rules/EC34/php/1GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC66/php/1GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC67/php/1GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC69/php/1GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC72/php/1GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC72/php/2GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC72/php/4GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC72/php/8GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC74/php/1GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/etsdiff-methodology.asciidoc diff --git a/ecocode-rules-specifications/src/main/rules/EC1/java/EC1.asciidoc b/ecocode-rules-specifications/src/main/rules/EC1/java/EC1.asciidoc index c7bc959b3..91ae3f7f0 100644 --- a/ecocode-rules-specifications/src/main/rules/EC1/java/EC1.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC1/java/EC1.asciidoc @@ -1,20 +1,23 @@ -

      The use of Spring repository in a loop induces unnecessary calculations by the CPU and therefore superfluous energy consumption.

      -

      Noncompliant Code Example

      -
      -		private final List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
      +The use of Spring repository in a loop induces unnecessary calculations by the CPU and therefore superfluous energy consumption.
       
      -		List<Employee> employees = new ArrayList<>();
      -		
      -		for (Integer id: ids) {
      -            Optional<Employee> employee = employeeRepository.findById(id); // Noncompliant
      -            if (employee.isPresent()) {
      -                employees.add(employee.get());
      -            }
      -        }
      +## Noncompliant Code Example
       
      -
      -

      Compliant Solution

      -
      -		private final List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
      -		List<Employee> employees = employeeRepository.findAllById(ids);
      -
      +```java +private final List ids = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + +List employees = new ArrayList<>(); + +for (Integer id: ids) { + Optional employee = employeeRepository.findById(id); // Noncompliant + if (employee.isPresent()) { + employees.add(employee.get()); + } +} +``` + +## Compliant Solution + +```java +private final List ids = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); +List employees = employeeRepository.findAllById(ids); +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC10/python/EC10.asciidoc b/ecocode-rules-specifications/src/main/rules/EC10/python/EC10.asciidoc index 131ab21f8..cf2483171 100644 --- a/ecocode-rules-specifications/src/main/rules/EC10/python/EC10.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC10/python/EC10.asciidoc @@ -1,8 +1,10 @@ -

      SVG images generated by common drawing softwares contains unnecessary data: calc layer, metadata, namespaces and comments.

      -

      Noncompliant Code Example

      -
      -<!-- Created with Inkscape (http://www.inkscape.org/) -->
      -<svg
      +SVG images generated by common drawing softwares contains unnecessary data: calc layer, metadata, namespaces and comments.
      +
      +## Noncompliant Code Example
      +
      +```xml
      +
      +
      +    
      +        
      -

      Compliant Solution

      -
      -<svg
      -    width="210mm"
      -    height="297mm"
      -    viewBox="0 0 210 297"
      -    xmlns="http://www.w3.org/2000/svg"
      -    xmlns:svg="http://www.w3.org/2000/svg">
      -    <g>
      -        <circle
      -            style="fill:#ff00ff;stroke-width:0.264583"
      -            id="path111"
      -            cx="104.02724"
      -            cy="152.19028"
      -            r="73.177132" />
      -    </g>
      -</svg>
      -
      + r="73.177132" /> + + +``` + +## Compliant Solution + +```xml + + + +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc b/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc index 7e5fcc2a0..0e56f2845 100644 --- a/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc @@ -1,31 +1,32 @@ -

      If we are using too many conditional if-else statements it will impact performance since JVM will have to compare the conditions. We can think of using a switch statement instead of multiple if-else if possible. Switch statement has a performance advantage over if – else.

      +If we are using too many conditional `if` – `else` statements it will impact performance since JVM will have to compare the conditions. We can think of using a switch statement instead of multiple `if` – `else` if possible. `switch` statement has a performance advantage over `if` – `else`. -

      Non-compliant Code Example

      -
      -		int index = 1;
      -        int nb = 2;
      +## Non-compliant Code Example
       
      -        if (nb > index) {
      -            nb = nb + index;
      -        } else {
      -            nb = nb - 1;
      -        }
      -        if (nb != index + 1) {
      -            nb = nb + index;
      -        } else {
      -            nb = nb - 1;
      -        }
      +```java
      +int index = 1;
      +int nb = 2;
       
      +if (nb > index) {
      +    nb = nb + index;
      +} else {
      +    nb = nb - 1;
      +}
      +if (nb != index + 1) {
      +    nb = nb + index;
      +} else {
      +    nb = nb - 1;
      +}
      +```
       
      -
      -

      Compliant Code Example

      -
      -        int index = 1;
      -        int nb = 2;
      +## Compliant Code Example
       
      -        if (nb > index) {
      -            nb = nb + index;
      -        } else {
      -            nb = nb - 1;
      -        }
      -
      +```java +int index = 1; +int nb = 2; + +if (nb > index) { + nb = nb + index; +} else { + nb = nb - 1; +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc b/ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc index 7f9e458fd..85d38acb6 100644 --- a/ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc @@ -1,73 +1,78 @@ -

      If possible, the utilisation of svg image format (or <svg/> html tag) is recommended over other image format.

      -

      Because SVGs are generally smaller than other image format, they’re less taxing on your server despite needing to render on load.

      -

      When to use SVG : -

        -
      • Your image is used for decorative website graphics, logos, icons, graphs and diagrams, and other simple images.
      • -
      • You image require animation.
      • -
      • You image need to be responsive and scale without lack of quality.
      • -
      -

      -

      Some advantages of using SVG: -

        -
      • SVGs are scalable and will render pixel-perfect at any resolution whereas JPEGs, PNGs and GIFs will not.
      • -
      • SVGs are vector images and therefore are usually much smaller in file-size than bitmap-based images.
      • -
      • SVGs can be embedded into the HTML which means they can be cached, edited directly using CSS and indexed for greater accessibility.
      • -
      • SVGs can be animated directly or by using CSS or JavaScript making it easy for web designers to add interactivity to a site.
      • -
      -

      - - -

      Noncompliant Code Example

      -
      -    ...
      -    img_jpg = "image.jpg"
      -    ...
      -
      -

      Compliant Solution

      -
      -    ...
      -    img_svg = "image.svg"
      -    ...
      -
      - -

      Noncompliant Code Example

      -
      -    public void foo() {
      -        ...
      -        image_format = testImage("image.jpg")
      -        ...
      -    }
      -
      -

      Compliant Solution

      -
      -    public void foo() {
      -        ...
      -        image_format = testImage("image.svg")
      -        ...
      -   }
      -
      - -

      Noncompliant Code Example

      -
      -    public void foo() {
      -        ...
      -        return '<html><img src="xx/xx/image.bmp"></html>'
      -        ...
      -    }
      -
      -

      Compliant Solution

      -
      -    public void foo() {
      -        ...
      -        return '<html><img src="xx/xx/image.svg"></html>'
      -        ...
      -   }
      -
      -     public void foo2() {
      -        ...
      -        return ('<html><svg width="100" height="100">' +
      -                '<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />' +
      -                '</svg></html>')
      -        ...
      -   }
      -
      +If possible, the utilisation of svg image format (or `` html tag) is recommended over other image format. + +Because SVGs are generally smaller than other image format, they’re less taxing on your server despite needing to render on load. + +When to use SVG : + +- Your image is used for decorative website graphics, logos, icons, graphs and diagrams, and other simple images. +- You image require animation. +- You image need to be responsive and scale without lack of quality. + +Some advantages of using SVG: + +- SVGs are scalable and will render pixel-perfect at any resolution whereas JPEGs, PNGs and GIFs will not. +- SVGs are vector images and therefore are usually much smaller in file-size than bitmap-based images. +- SVGs can be embedded into the HTML which means they can be cached, edited directly using CSS and indexed for greater accessibility. +- SVGs can be animated directly or by using CSS or JavaScript making it easy for web designers to add interactivity to a site. + +## Noncompliant Code Example + +``` +img_jpg = "image.jpg" +``` + +## Compliant Solution + +``` +img_svg = "image.svg" +``` + +## Noncompliant Code Example + +``` +public void foo() { + // ... + image_format = testImage("image.jpg") + // ... +} +``` + +## Compliant Solution + +``` +public void foo() { + // ... + image_format = testImage("image.svg") + // ... +} +``` + +## Noncompliant Code Example + +``` +public void foo() { + // ... + return '' + // ... +} +``` + +## Compliant Solution + +``` +public void foo() { + // ... + return '' + // ... +} +``` + +Or + +``` + public void foo() { + // ... + return ('') + // ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc b/ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc index 0294f0a03..c42338993 100644 --- a/ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc @@ -1,9 +1,13 @@ -

      Use of methods for basic operations

      -

      Noncompliant Code Example

      -
      -	$min = min($a, $b);  // Noncompliant
      -
      -

      Compliant Solution

      -
      -	$min = $a < $b ? $a : $b;
      -
      +Use of methods for basic operations + +## Noncompliant Code Example + +```php +$min = min($a, $b); // Noncompliant +``` + +## Compliant Solution + +```php +$min = $a < $b ? $a : $b; +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC27/java/EC27.asciidoc b/ecocode-rules-specifications/src/main/rules/EC27/java/EC27.asciidoc index 8bfb72e6b..455e0a137 100644 --- a/ecocode-rules-specifications/src/main/rules/EC27/java/EC27.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC27/java/EC27.asciidoc @@ -1,24 +1,28 @@ -

      Using System.arraycopy to copy arrays

      -

      - Programs spend most of the time in loops. These can be resource consuming, especially when they integrate heavy processing (IO access). Moreover, the size of the data and processing inside the loops will not allow full use of hardware mechanisms such as the cache or compiler optimization mechanisms.
      - For example, an array copy is potentially a non-performance source if it is poorly designed. Indeed, the use of a single copy loop can be twice as consuming as dedicated methods.
      - Loops must be optimized to reduce processing time and make full use of hardware and processor mechanisms and optimizations.
      - In the case of table copying (table), the native System.arraycopy.
      - We can also use copyOf or clone that are slightly less efficient.
      - The looping method will be outlawed. -

      -

      Noncompliant Code Example

      -
      -	int len = array.length;
      -	boolean[] copy = new boolean[array.length];
      -	for (int i = 0; i < len; i++) {
      -  		copy[i] = array[i];  // Noncompliant
      -	}
      -	return copy;
      -
      -

      Compliant Solution

      -
      -	int[] copy = new int[array.length];
      -	System.arraycopy(array, 0, copy, 0, array.length);
      -	return copy;
      -
      +Using `System.arraycopy` to copy arrays + +Programs spend most of the time in loops. These can be resource consuming, especially when they integrate heavy processing (IO access). Moreover, the size of the data and processing inside the loops will not allow full use of hardware mechanisms such as the cache or compiler optimization mechanisms. + +For example, an array copy is potentially a non-performance source if it is poorly designed. Indeed, the use of a single copy loop can be twice as consuming as dedicated methods. +Loops must be optimized to reduce processing time and make full use of hardware and processor mechanisms and optimizations. +In the case of table copying (table), use the native `System.arraycopy`. +We can also use `copyOf` or `clone` that are slightly less efficient. +The looping method will be outlawed. + +## Noncompliant Code Example + +```java +int len = array.length; +boolean[] copy = new boolean[array.length]; +for (int i = 0; i < len; i++) { + copy[i] = array[i]; // Noncompliant +} +return copy; +``` + +## Compliant Solution + +```java +int[] copy = new int[array.length]; +System.arraycopy(array, 0, copy, 0, array.length); +return copy; +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc b/ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc index d37bcef22..841ee9f8c 100644 --- a/ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc @@ -1,29 +1,30 @@ -

      Optimize read file exception

      -

      Noncompliant Code Example

      -
      -		public void readPreferences(String filename) {
      -		  //...
      -		  InputStream in = null;
      -		  try {
      -			in = new FileInputStream(filename);
      -		  } catch (FileNotFoundException e) {
      -			logger.log(e);
      -		  }
      -		  in.read(...);
      -		  //...
      -		}
      +Optimize read file exception
       
      -
      -

      Compliant Solution

      -
      -		public void readPreferences(String filename)
      -			throws IllegalArgumentException,
      -				   FileNotFoundException, IOException {
      -		  if (filename == null) {
      -			throw new IllegalArgumentException ("filename is null");
      -		  }  //if
      -		  //...
      -		  InputStream in = new FileInputStream(filename);
      -		  //...
      -		}
      -
      +## Noncompliant Code Example + +```java +public void readPreferences(String filename) { + //... + InputStream in = null; + try { + in = new FileInputStream(filename); + } catch (FileNotFoundException e) { + logger.log(e); + } + in.read(...); + //... +} +``` + +## Compliant Solution + +```java +public void readPreferences(String filename) throws IllegalArgumentException, FileNotFoundException, IOException { + if (filename == null) { + throw new IllegalArgumentException ("filename is null"); + } + //... + InputStream in = new FileInputStream(filename); + //... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc b/ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc index b347d7141..49fcb223e 100644 --- a/ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc @@ -1,19 +1,22 @@ -

      When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. The example provided below illustrates what should be avoided.

      -

      Noncompliant Code Example

      -
      -		List<String> objList = getData();
      +When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. The example provided below illustrates what should be avoided.
       
      -        for (int i = 0; i < objList.size(); i++) {  // Noncompliant
      -            // execute code
      -        }
      +## Noncompliant Code Example
       
      -
      -

      Compliant Solution

      -
      -        List<String> objList = getData();
      +```java
      +List objList = getData();
       
      -        int size = objList.size();
      -        for (int i = 0; i < size; i++) {
      -            // execute code
      -        }
      -
      +for (int i = 0; i < objList.size(); i++) { // Noncompliant + // execute code +} +``` + +## Compliant Solution + +```java +List objList = getData(); + +int size = objList.size(); +for (int i = 0; i < size; i++) { + // execute code +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC3/php/EC3.asciidoc b/ecocode-rules-specifications/src/main/rules/EC3/php/EC3.asciidoc index 3eace53ff..9c4d5bb81 100644 --- a/ecocode-rules-specifications/src/main/rules/EC3/php/EC3.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC3/php/EC3.asciidoc @@ -1,93 +1,96 @@ -

      When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power.

      -

      NB : note that we are using the count() method to get the size of an array but it would work the same with the sizeof() and iterator_count() methods

      - -

      Noncompliant Code Examples

      -
      -	$array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
      -
      -	// FOR STATEMENTS / Right operand
      -	for ($i = 0; $i < count($array); ++$i) {
      -		var_dump($array[$i]);
      -	}
      -
      -	// FOR STATEMENTS / Left operand
      -	for ($i = 0; count($array) > $i; ++$i) {
      -		var_dump($array[$i]);
      -	}
      -
      -	// WHILE STATEMENTS / Right operand
      -	$i = 0;
      -	while($i < count($array)) {
      -		var_dump($array[$i]);
      -		++$i;
      -	}
      -
      -	// WHILE STATEMENTS / Left operand
      -	$i = 0;
      -	while(count($array) > $i) {
      -		var_dump($array[$i]);
      -		++$i;
      -	}
      -
      -	// DO WHILE STATEMENTS / Right operand
      -	$i = 0;
      -	do {
      -		var_dump($array[$i]);
      -		++$i;
      -	} while ($i < count($array));
      -
      -	// DO WHILE STATEMENTS / Left operand
      -	$i = 0;
      -	do {
      -		var_dump($array[$i]);
      -		++$i;
      -	} while (count($array) > $i);
      -
      - -

      Compliant Solution

      -
      -	$array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
      -	// FOR STATEMENTS / Right operand
      -	$size = sizeof($array);
      -	for ($i = 0; $i < $size; ++$i) {
      -		var_dump($array[$i]);
      -	}
      -
      -	// FOR STATEMENTS / Left operand
      -	$size = sizeof($array);
      -	for ($i = 0; $size > $i; ++$i) {
      -		var_dump($array[$i]);
      -	}
      -
      -	// WHILE STATEMENTS / Right operand
      -	$i = 0;
      -	$size = count($array);
      -	while($i < $size) {
      -		var_dump($array[$i]);
      -		++$i;
      -	}
      -
      -	// WHILE STATEMENTS / Left operand
      -	$i = 0;
      -	$size = count($array);
      -	while($size > $i) {
      -		var_dump($array[$i]);
      -		++$i;
      -	}
      -
      -	// DO WHILE STATEMENTS / Right operand
      -	$i = 0;
      -	$size = count($array);
      -	do {
      -		var_dump($array[$i]);
      -		++$i;
      -	} while ($i < $size);
      -
      -	// DO WHILE STATEMENTS / Left operand
      -	$i = 0;
      -	$size = count($array);
      -	do {
      -		var_dump($array[$i]);
      -		++$i;
      -	} while ($size > $i);
      -
      +When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. + +NB : note that we are using the `count()` method to get the size of an array but it would work the same with the `sizeof()` and `iterator_count()` methods. + +## Noncompliant Code Example + +```php +$array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea'); + +// FOR STATEMENTS / Right operand +for ($i = 0; $i < count($array); ++$i) { + var_dump($array[$i]); +} + +// FOR STATEMENTS / Left operand +for ($i = 0; count($array) > $i; ++$i) { + var_dump($array[$i]); +} + +// WHILE STATEMENTS / Right operand +$i = 0; +while($i < count($array)) { + var_dump($array[$i]); + ++$i; +} + +// WHILE STATEMENTS / Left operand +$i = 0; +while(count($array) > $i) { + var_dump($array[$i]); + ++$i; +} + +// DO WHILE STATEMENTS / Right operand +$i = 0; +do { + var_dump($array[$i]); + ++$i; +} while ($i < count($array)); + +// DO WHILE STATEMENTS / Left operand +$i = 0; +do { + var_dump($array[$i]); + ++$i; +} while (count($array) > $i); +``` + +## Compliant Solution + +```php +$array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea'); +// FOR STATEMENTS / Right operand +$size = sizeof($array); +for ($i = 0; $i < $size; ++$i) { + var_dump($array[$i]); +} + +// FOR STATEMENTS / Left operand +$size = sizeof($array); +for ($i = 0; $size > $i; ++$i) { + var_dump($array[$i]); +} + +// WHILE STATEMENTS / Right operand +$i = 0; +$size = count($array); +while($i < $size) { + var_dump($array[$i]); + ++$i; +} + +// WHILE STATEMENTS / Left operand +$i = 0; +$size = count($array); +while($size > $i) { + var_dump($array[$i]); + ++$i; +} + +// DO WHILE STATEMENTS / Right operand +$i = 0; +$size = count($array); +do { + var_dump($array[$i]); + ++$i; +} while ($i < $size); + +// DO WHILE STATEMENTS / Left operand +$i = 0; +$size = count($array); +do { + var_dump($array[$i]); + ++$i; +} while ($size > $i); +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc b/ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc index 253090269..00c2ac907 100644 --- a/ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc @@ -1,19 +1,21 @@ -

      - If you know in advance how many characters would be appended, initialize builder/buffer with the appropriate size. - They will thus never have to be resized. - This saves CPU cycles and therefore consumes less energy. -

      -

      Noncompliant Code Example

      -
      -    StringBuilder sb = new StringBuilder(); // Noncompliant
      -    for (int i = 0; i < 100; i++) {
      -       sb.append(...);
      -    }
      -
      -

      Compliant Solution

      -
      -    StringBuilder sb = new StringBuilder(100);
      -    for (int i = 0; i < 100; i++) {
      -       sb.append(...);
      -    }
      -
      +If you know in advance how many characters would be appended, initialize builder/buffer with the appropriate size. +They will thus never have to be resized. +This saves CPU cycles and therefore consumes less energy. + +## Noncompliant Code Example + +```java +StringBuilder sb = new StringBuilder(); // Noncompliant +for (int i = 0; i < 100; i++) { + sb.append(...); +} +``` + +## Compliant Solution + +```java +StringBuilder sb = new StringBuilder(100); +for (int i = 0; i < 100; i++) { + sb.append(...); +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC34/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC34/php/1GB.etsdiff.csv new file mode 100644 index 000000000..5b56c3789 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC34/php/1GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),515.855638,516.9188409999999 +Transfer (B),1579453,1579457 +Storage (B),637549804,637549804 diff --git a/ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc b/ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc index 5b8bd83c2..f7b2ab71d 100644 --- a/ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc @@ -1,7 +1,10 @@ -

      Inside complex code parts (for exemple multiple loops, complex data constructions...), avoid using try...catch...finally.

      -

      When an exception is thrown, a variable (the exception itself) is created in a catch block and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.

      -

      Noncompliant Code Example

      -
      +Inside complex code parts (for exemple multiple loops, complex data constructions...), avoid using try...catch...finally.
      +
      +When an exception is thrown, a variable (the exception itself) is created in a catch block and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.
      +
      +## Noncompliant Code Example
      +
      +```php
       try
       {
         $picture = PDF_open_image_file($PDF, "jpeg", $imgFile, "", 0); // This is the original statement, this works on PHP4
      @@ -11,10 +14,11 @@ catch(Exception $ex)
         $msg = "Error opening $imgFile for Product $row['Identifier']";
         throw new Exception($msg);
       }
      +```
       
      -
      -

      Compliant Solution

      -
      +## Compliant Solution
      +
      +```php
       //try
       if (file_exists($imgFile)) {
           $picture = PDF_open_image_file($PDF, "jpeg", $imgFile, "", 0);
      @@ -25,85 +29,17 @@ if (!$picture) {
          $msg = "Error opening $imgFile for Product $row['Identifier']";
          print $msg;
       }
      -
      -

      The three sources of impacts of a code identified are:

      -- Energy (measured in joules) -
      - Transfer (measured in Bytes) -
      - Storage (measured in Bytes)
      -
      The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. -
      The ETSdiff tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). -
      The results generated by ETSdiff must help define the interest of the rule reported by Sonarqube in the context of the code analyzed. -
      -

      Case for a 1GB database:

      -
      - ETSdiff percent comparison -
      -

      Total:

      - - - - - - - - - - - - - - - - - - - - - - - -
      -
      -
      Compliant
      -
      -
      -
      -
      Non-compliant
      -
      -
      -
      -
      Energy
      -
      -
      -
      -
      515.855638
      -
      -
      -
      -
      516.9188409999999
      -
      -
      -
      -
      Transfer
      -
      -
      -
      -
      1579453
      -
      -
      -
      -
      1579457
      -
      -
      -
      -
      Storage
      -
      -
      -
      -
      637549804
      -
      -
      -
      -
      637549804
      -
      -
      +``` + +include::../../etsdiff-methodology.asciidoc[] + +## Case for a 1GB database: + +image::https://live.staticflickr.com/65535/52622382871_f19da08db4_o.png[ETSdiff percent comparison] + +[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant + +include::1GB.etsdiff.csv[] +|=== diff --git a/ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc b/ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc index d90cacc9e..14b3c3c5b 100644 --- a/ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc @@ -1,8 +1,10 @@ -

      Inside complex code parts (for example multiple loops, complex data constructions...), avoid using try...catch...finally. -

      When an exception is thrown, a variable (the exception itself) is created in a catch block, and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.

      -

      -

      Noncompliant Code Example

      -
      +Inside complex code parts (for example multiple loops, complex data constructions...), avoid using try...catch...finally.
      +
      +When an exception is thrown, a variable (the exception itself) is created in a catch block, and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.
      +
      +## Noncompliant Code Example
      +
      +```python
       try:
           f = open(path)
           print(fh.read())
      @@ -10,12 +12,14 @@ except:
           print('No such file '+path
       finally:
           f.close()
      +```
       
      -
      -

      Compliant Solution

      -
      +## Compliant Solution
      +
      +```python
       if os.path.isfile(path):
         fh = open(path, 'r')
         print(fh.read())
         fh.close
      -
      +``` + diff --git a/ecocode-rules-specifications/src/main/rules/EC4/java/EC4.asciidoc b/ecocode-rules-specifications/src/main/rules/EC4/java/EC4.asciidoc index e95fd679d..f8763b4ed 100644 --- a/ecocode-rules-specifications/src/main/rules/EC4/java/EC4.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC4/java/EC4.asciidoc @@ -1,34 +1,37 @@ -

      - Prefer local variables as parameters -

      -

      When calling a global variable, the interpretation engine must check that it exists in all the scopes, that it has a value, etc. Passing global variables as arguments gives them the status of local variables inside the function, thus saving computing time (CPU cycles). -

      -

      -CASE 1 (Avoid as possible):
      -You are back on the service code. You see that the func1() uses globalVariabl1. Okay, but whats its value by now ? How does it change ? Who mutates the globalVariabl1 before it comes to this function ? What have been the sequence of all these mutations ? You would have no idea. It will be quite difficult to figure all this out. -
      -CASE 2 (Recommended):
      -You are back to you code, and see that the func0() fetches something and then passes it to func1(param1) as a parameter. You clearly know what the data is, how does it gets here. -

      -

      Noncompliant Code Example

      -
      -    var aGlobal = new String('Hello');
      -
      -    function globalLength(){
      -        length = aGlobal.length;
      -        console.log(length);
      -    }
      -
      -    globalLength();
      -
      -

      Compliant Solution

      -
      -    var aGlobal = new String('Hello');
      -
      -    function someVarLength(str){
      -        length = str.length;
      -        console.log(length);
      -    }
      -
      -    somVarLength(aGlobal);
      -
      \ No newline at end of file +Prefer local variables as parameters + +When calling a global variable, the interpretation engine must check that it exists in all the scopes, that it has a value, etc. Passing global variables as arguments gives them the status of local variables inside the function, thus saving computing time (CPU cycles). + +## CASE 1 (Avoid as possible) + +You are back on the service code. You see that the `func1()` uses `globalVariabl1`. Okay, but whats its value by now ? How does it change ? Who mutates the `globalVariabl1` before it comes to this function ? What have been the sequence of all these mutations ? You would have no idea. It will be quite difficult to figure all this out. + +## CASE 2 (Recommended) + +You are back to you code, and see that the `func0()` fetches something and then passes it to `func1(param1)` as a parameter. You clearly know what the data is, how does it gets here. + +## Noncompliant Code Example + +```java +var aGlobal = new String('Hello'); + +function globalLength(){ + length = aGlobal.length; + console.log(length); +} + +globalLength(); +``` + +## Compliant Solution + +```java +var aGlobal = new String('Hello'); + +function someVarLength(str){ + length = str.length; + console.log(length); +} + +somVarLength(aGlobal); +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc b/ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc index 6e9687fa7..94021a9e6 100644 --- a/ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc @@ -1,27 +1,29 @@ -

      - Prefer local variables as parameters -

      -

      When calling a global variable, the interpretation engine must check that it exists in all the scopes, that it has a value, etc. Passing global variables as arguments gives them the status of local variables inside the function, thus saving computing time (CPU cycles). -

      -

      Noncompliant Code Example

      -
      -  var aGlobal = new String('Hello');
      -
      -  function globalLength(){
      +Prefer local variables as parameters
      +
      +When calling a global variable, the interpretation engine must check that it exists in all the scopes, that it has a value, etc. Passing global variables as arguments gives them the status of local variables inside the function, thus saving computing time (CPU cycles).
      +
      +## Noncompliant Code Example
      +
      +```php
      +var aGlobal = new String('Hello');
      +
      +function globalLength(){
           length = aGlobal.length;
           console.log(length);
      -  }
      +}
      +
      +globalLength();
      +```
      +
      +## Compliant Solution
       
      -  globalLength();
      -
      -

      Compliant Solution

      -
      -  var aGlobal = new String('Hello');
      +```php
      +var aGlobal = new String('Hello');
       
      -  function someVarLength(str){
      +function someVarLength(str){
           length = str.length;
           console.log(length);
      -  }
      +}
       
      -  somVarLength(aGlobal);
      -
      \ No newline at end of file +somVarLength(aGlobal); +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc b/ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc index c92e7e5be..b777840a9 100644 --- a/ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc @@ -1,20 +1,24 @@ -

      When function calls global variables, a lot a CPU cycles is consumed.

      -

      Noncompliant Code Example

      -
      +When function calls global variables, a lot a CPU cycles is consumed.
      +
      +## Noncompliant Code Example
      +
      +```python
       global_var = 'foo'
       def print_global_var_details():
           print(len(global_var)) # Noncompliant
           print('Global var : ', global_var) # Noncompliant
           print('Global var : ' + global_var) # Noncompliant
       print_global_var_details()
      -
      -

      Compliant Solution

      -
      +```
      +
      +## Compliant Solution
      +
      +```python
       global_var = 'foo';
       def print_var_details(local_var) {
      -  print(len(local_var));
      -  print('Var : ', local_var)
      -  print('Var : ' + local_var)
      +    print(len(local_var));
      +    print('Var : ', local_var)
      +    print('Var : ' + local_var)
       }
       print_length(global_var);
      -
      +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC404/python/EC404.asciidoc b/ecocode-rules-specifications/src/main/rules/EC404/python/EC404.asciidoc index f7c47727f..4a0738f9f 100644 --- a/ecocode-rules-specifications/src/main/rules/EC404/python/EC404.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC404/python/EC404.asciidoc @@ -1,13 +1,20 @@ -

      Use generator comprehension instead of list comprehension in for loop declaration.

      -

      Python generators resemble lazy lists from other programming languages: when iterated over, they compute their values on the fly. They lack some list behaviors (indexing, len method, ...) but are memory-efficient, as they do not store each of their values in memory, unlike lists. Thus, when declared in a for-loop declaration, list comprehensions can be safely replaced with generator comprehensions.

      -

      For more details on list comprehensions vs generator comprehensions, see Python documentation.

      -

      Noncompliant Code Example

      -
      +Use generator comprehension instead of list comprehension in for loop declaration.
      +
      +Python generators resemble lazy lists from other programming languages: when iterated over, they compute their values on the fly. They lack some list behaviors (indexing, len method, ...) but are memory-efficient, as they do not store each of their values in memory, unlike lists. Thus, when declared in a for-loop declaration, list comprehensions can be safely replaced with generator comprehensions.
      +
      +For more details on list comprehensions vs generator comprehensions, see https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions[Python documentation].
      +
      +## Noncompliant Code Example
      +
      +```python
       for var in [var2 for var2 in range(100)]:
           ...
      -
      -

      Compliant Solution

      -
      +
      +```
      +
      +## Compliant Solution
      +
      +```python
       for var in (var2 for var2 in range(100)):
           ...
      -
      +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC5/java/EC5.asciidoc b/ecocode-rules-specifications/src/main/rules/EC5/java/EC5.asciidoc index 3fd5bb834..229a3503d 100644 --- a/ecocode-rules-specifications/src/main/rules/EC5/java/EC5.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC5/java/EC5.asciidoc @@ -1,18 +1,22 @@ -

      Use PreparedStatement instead of Statement, because SQL will only commit the query once, whereas if you used only one statement, it would commit the query every time and thus induce unnecessary calculations by the CPU and therefore superfluous energy consumption.

      -

      Noncompliant Code Example

      -
      -    public void select() {
      -        Statement statement = connection.createStatement();
      -        statement.executeUpdate("INSERT INTO persons(id, name) VALUES(2, 'Toto')");  // Noncompliant
      -    }
      -
      -

      Compliant Solution

      -
      -    public void select() {
      -        PreparedStatement statement = connection.prepareStatement(INSERT INTO persons(id, name) VALUES(?, ?));
      +Use `PreparedStatement` instead of `Statement`, because SQL will only commit the query once, whereas if you used only one statement, it would commit the query every time and thus induce unnecessary calculations by the CPU and therefore superfluous energy consumption.
       
      -        statement.setInt(1, 2);
      -        statement.setString(2, "Toto");
      -        statement.executeQuery();
      -    }
      -
      +## Noncompliant Code Example + +```java +public void select() { + Statement statement = connection.createStatement(); + statement.executeUpdate("INSERT INTO persons(id, name) VALUES(2, 'John DOE')"); // Noncompliant +} +``` + +## Compliant Solution + +```java +public void select() { + PreparedStatement statement = connection.prepareStatement(INSERT INTO persons(id, name) VALUES(?, ?)); + + statement.setInt(1, 2); + statement.setString(2, "John DOE"); + statement.executeQuery(); +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC53/java/EC53.asciidoc b/ecocode-rules-specifications/src/main/rules/EC53/java/EC53.asciidoc index b1d548c92..924efda63 100644 --- a/ecocode-rules-specifications/src/main/rules/EC53/java/EC53.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC53/java/EC53.asciidoc @@ -1,18 +1,21 @@ -

      Using List instead of Arrays with Foreach save CPU cycles calculations and RAM consumption.

      -

      Noncompliant Code Example

      -
      -		private final Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
      +Using List instead of Arrays with Foreach save CPU cycles calculations and RAM consumption.
       
      -		for (Integer i : intArray) {
      -			...
      -		}
      +## Noncompliant Code Example
       
      -
      -

      Compliant Solution

      -
      -		private final List<Integer> intList = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
      +```java
      +private final Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
       
      -		for (Integer i : intList) {
      -			...
      -		}
      -
      +for (Integer i : intArray) { + // ... +} +``` + +## Compliant Solution + +```java +private final List intList = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + +for (Integer i : intList) { + // ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC63/java/EC63.asciidoc b/ecocode-rules-specifications/src/main/rules/EC63/java/EC63.asciidoc index be6d491d4..9d3ca796d 100644 --- a/ecocode-rules-specifications/src/main/rules/EC63/java/EC63.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC63/java/EC63.asciidoc @@ -1,12 +1,17 @@ -

      Do not unnecessarily assign values to variables. It increases the use of RAM memory.

      -

      Noncompliant Code Example

      -
      +Do not unnecessarily assign values to variables. It increases the use of RAM memory.
      +
      +## Noncompliant Code Example
      +
      +```java
       String var1 = getValue();
       return var1;
       
       String var2 = "hello"
      -var2 = "world"        //Non compliant cause never assigned 
      +var2 = "world"        //Non compliant cause never assigned
      +```
      +
      +## Compliant Solution
       
      -
      -

      Compliant Solution

      -
      return getValue();
      +```java +return getValue(); +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC66/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC66/php/1GB.etsdiff.csv new file mode 100644 index 000000000..4765a99fe --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC66/php/1GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),3.041966,1.2651545000000002 +Transfer (B),68520884,68588123 +Storage (B),637548795,637548795 diff --git a/ecocode-rules-specifications/src/main/rules/EC66/php/EC66.asciidoc b/ecocode-rules-specifications/src/main/rules/EC66/php/EC66.asciidoc index 233604feb..8af551481 100644 --- a/ecocode-rules-specifications/src/main/rules/EC66/php/EC66.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC66/php/EC66.asciidoc @@ -1,94 +1,30 @@ -

      PHP allows declaring a string with simple or double quotes. Using double quotes allows developers to insert variables which will be substituted during execution. When the string has no variables, using single quotes prevents PHP from searching for non-existent variables. It will save CPU cycles consumption and RAM usage.

      -

      Noncompliant Code Example

      -
      +PHP allows declaring a string with simple or double quotes. Using double quotes allows developers to insert variables which will be substituted during execution. When the string has no variables, using single quotes prevents PHP from searching for non-existent variables. It will save CPU cycles consumption and RAM usage.
      +
      +## Noncompliant Code Example
      +
      +```php
       myFunction("name", "age", "IsStudent");
      -  $lastName = "Hugo";
      -  $concatenatedString = "$lastName is a student";
      -
      -

      Compliant Solution

      -
      +    $lastName = "Hugo";
      +    $concatenatedString = "$lastName is a student";
      +```
      +
      +## Compliant Solution
      +
      +```php
       myFunction('name', 'age', 'IsStudent');
           $lastName = 'Hugo';
           $concatenatedString = $lastName . 'is a student';
      -
      -

      The three sources of impacts of a code identified are:

      -- Energy (measured in joules) -
      - Transfer (measured in Bytes) -
      - Storage (measured in Bytes)
      -
      The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. -
      The ETSdiff tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). -
      The results generated by ETSdiff must help define the interest of the rule reported by Sonarqube in the context of the code analyzed. -
      -

      Case for a 1GB database:

      -
      - ETSdiff percent comparison -
      -

      Total:

      - - - - - - - - - - - - - - - - - - - - - - - -
      -
      -
      Compliant
      -
      -
      -
      -
      Non-compliant
      -
      -
      -
      -
      Energy
      -
      -
      -
      -
      3.041966
      -
      -
      -
      -
      1.2651545000000002
      -
      -
      -
      -
      Transfer
      -
      -
      -
      -
      68520884
      -
      -
      -
      -
      68588123
      -
      -
      -
      -
      Storage
      -
      -
      -
      -
      637548795
      -
      -
      -
      -
      637548795
      -
      -
      +``` + +include::../../etsdiff-methodology.asciidoc[] + +## Case for a 1GB database: + +image::https://live.staticflickr.com/65535/52621866212_de15608a41_o.png[ETSdiff percent comparison] + +[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant + +include::1GB.etsdiff.csv[] +|=== diff --git a/ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc b/ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc index 0a94f3529..09e0eda41 100644 --- a/ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc @@ -1,27 +1,31 @@ -

      - The shape using the quotation marks (") allows the developer to insert variables that will be substituted at run time.
      - But if the string does not have a variable, use quotes (') instead.
      - Thus, language will not look for variables to substitute, which will reduce the consumption of CPU cycles. -

      -

      Noncompliant Code Example

      -
      -    # in variables
      -    firstname = "Andrea" # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}}
      -
      -    # in functions
      -    def my_function(name, age):
      -        print(name + 'is' + age + ' yo.')
      -
      -    my_function("Robert", 12) # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}}
      -
      -

      Compliant Solution

      -
      -    # in variables
      -    firstname = 'Andrea'
      -
      -    # in functions
      -    def my_function(name, age):
      -        print(name + 'is' + age + ' yo.')
      -
      -    my_function('Robert', 12)
      -
      +The shape using the quotation marks (") allows the developer to insert variables that will be substituted at run time. + +But if the string does not have a variable, use quotes (') instead. + +Thus, language will not look for variables to substitute, which will reduce the consumption of CPU cycles. + +## Noncompliant Code Example + +```python +# in variables +firstname = "Andrea" # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}} + +# in functions +def my_function(name, age): + print(name + 'is' + age + ' yo.') + +my_function("Robert", 12) # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}} +``` + +## Compliant Solution + +```python +# in variables +firstname = 'Andrea' + +# in functions +def my_function(name, age): + print(name + 'is' + age + ' yo.') + +my_function('Robert', 12) +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc b/ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc index 3c55323e5..a0c7b961a 100644 --- a/ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc @@ -1,7 +1,13 @@ -

      The form $i++ creates a temporary variable whereas ++$i does not. It save CPU cycles.

      -

      Noncompliant Code Example

      -
      +The form `$i++` creates a temporary variable whereas `++$i` does not. It save CPU cycles.
      +
      +## Noncompliant Code Example
      +
      +```java
       i++  // Noncompliant
      -
      -

      Compliant Solution

      -
      ++i
      +``` + +## Compliant Solution + +```java +++i +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC67/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC67/php/1GB.etsdiff.csv new file mode 100644 index 000000000..c79e54fc0 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC67/php/1GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),1.8163645000000002,0.2613885000000001 +Transfer (B),11265758,11290494 +Storage (B),637548673,637548673 diff --git a/ecocode-rules-specifications/src/main/rules/EC67/php/EC67.asciidoc b/ecocode-rules-specifications/src/main/rules/EC67/php/EC67.asciidoc index 6e087ebf4..9a025ea99 100644 --- a/ecocode-rules-specifications/src/main/rules/EC67/php/EC67.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC67/php/EC67.asciidoc @@ -1,88 +1,26 @@ -

      The form $i++ creates a temporary variable whereas ++$i does not. It save CPU cycles.

      -

      Noncompliant Code Example

      -
      +The form `$i++` creates a temporary variable whereas `++$i` does not. It save CPU cycles.
      +
      +## Noncompliant Code Example
      +
      +```php
       $i++
      -
      -

      Compliant Solution

      -
      ++$i
      -

      The three sources of impacts of a code identified are:

      -- Energy (measured in joules) -
      - Transfer (measured in Bytes) -
      - Storage (measured in Bytes)
      -
      The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. -
      The ETSdiff tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). -
      The results generated by ETSdiff must help define the interest of the rule reported by Sonarqube in the context of the code analyzed. -
      -

      Case for a 1GB database:

      -
      - ETSdiff percent comparison -
      -

      Total:

      - - - - - - - - - - - - - - - - - - - - - - - -
      -
      -
      Compliant
      -
      -
      -
      -
      Non-compliant
      -
      -
      -
      -
      Energy
      -
      -
      -
      -
      1.8163645000000002
      -
      -
      -
      -
      0.2613885000000001
      -
      -
      -
      -
      Transfer
      -
      -
      -
      -
      11265758
      -
      -
      -
      -
      11290494
      -
      -
      -
      -
      Storage
      -
      -
      -
      -
      637548673
      -
      -
      -
      -
      637548673
      -
      -
      \ No newline at end of file +``` + +## Compliant Solution + +```php +++$i +``` + +include::../../etsdiff-methodology.asciidoc[] + +## Case for a 1GB database: + +image::https://live.staticflickr.com/65535/52622379586_f84c767111_o.png[ETSdiff percent comparison] + +[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant + +include::1GB.etsdiff.csv[] +|=== diff --git a/ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc b/ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc index 5d8c46aa1..e32cd94db 100644 --- a/ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc @@ -1,23 +1,24 @@ -

      Do not call a function when declaring a for-type loop in order to avoid function calls each iterations. It saves CPU cycles.

      -

      Noncompliant Code Example

      -
      -    public void foo() {
      -        for (int i = 0; i < getMyValue(); i++) {  // Noncompliant
      -            System.out.println(i);
      -            boolean b = getMyValue() > 6;
      -        }
      -    }
      +Do not call a function when declaring a for-type loop in order to avoid function calls each iterations. It saves CPU cycles.
       
      -
      -

      Compliant Solution

      -
      +## Noncompliant Code Example
       
      -    public void foo() {
      -        int myValue =  getMyValue();
      -        for (int i = 0; i < myValue; i++) {
      -            System.out.println(i);
      -            boolean b = getMyValue() > 6;
      -        }
      +```java
      +public void foo() {
      +    for (int i = 0; i < getMyValue(); i++) {  // Noncompliant
      +        System.out.println(i);
      +        boolean b = getMyValue() > 6;
           }
      +}
      +```
      +
      +## Compliant Solution
       
      -
      +```java +public void foo() { + int myValue = getMyValue(); + for (int i = 0; i < myValue; i++) { + System.out.println(i); + boolean b = getMyValue() > 6; + } +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC69/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC69/php/1GB.etsdiff.csv new file mode 100644 index 000000000..227f4def5 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC69/php/1GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),144.635057,144.58341249999998 +Transfer (B),50000,50004 +Storage (B),637549590,637549590 diff --git a/ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc b/ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc index c71d96a37..0da3cde83 100644 --- a/ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc @@ -1,12 +1,16 @@ -

      Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.

      -

      Noncompliant Code Example

      -
      +Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.
      +
      +## Noncompliant Code Example
      +
      +```php
       for ($i = 0; $i <= foo(); $i++) {  // Noncompliant
       	// ......
       }
      -
      -

      Compliant Solution

      -
      +```
      +
      +## Compliant Solution
      +
      +```php
       $maxI = foo();
       for ($i = 0; $i <= $maxI; $i++) {
         .....
      @@ -17,88 +21,18 @@ for ($i = 0; $i <= $maxI; $i++) {
       for ($i = 0, $maxI = foo(); $i <= $maxI; $i++) {
         .....
       }
      -}
      +} +``` + +include::../../etsdiff-methodology.asciidoc[] + +## Case for a 1GB database: -

      The three sources of impacts of a code identified are:

      -- Energy (measured in joules) -
      - Transfer (measured in Bytes) -
      - Storage (measured in Bytes)
      -
      The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. -
      The ETSdiff tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). -
      The results generated by ETSdiff must help define the interest of the rule reported by Sonarqube in the context of the code analyzed. -
      +image::https://live.staticflickr.com/65535/52622634654_bf3c3d9ba8_o.png[ETSdiff percent comparison] -

      Case for a 1GB database:

      -
      - ETSdiff percent comparison -
      +[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant -

      Total:

      - - - - - - - - - - - - - - - - - - - - - - - -
      -
      -
      Compliant
      -
      -
      -
      -
      Non-compliant
      -
      -
      -
      -
      Energy
      -
      -
      -
      -
      144.635057
      -
      -
      -
      -
      144.58341249999998
      -
      -
      -
      -
      Transfer
      -
      -
      -
      -
      50000
      -
      -
      -
      -
      50004
      -
      -
      -
      -
      Storage
      -
      -
      -
      -
      637549590
      -
      -
      -
      -
      637549590
      -
      -
      +include::1GB.etsdiff.csv[] +|=== diff --git a/ecocode-rules-specifications/src/main/rules/EC69/python/EC69.asciidoc b/ecocode-rules-specifications/src/main/rules/EC69/python/EC69.asciidoc index 2c3c64ff1..3d73ce30a 100644 --- a/ecocode-rules-specifications/src/main/rules/EC69/python/EC69.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC69/python/EC69.asciidoc @@ -1,13 +1,17 @@ -

      Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.

      -

      Noncompliant Code Example

      -
      +Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.
      +
      +## Noncompliant Code Example
      +
      +```python
       for i in my_function():  # Noncompliant
           ......
      +```
       
      -
      -

      Compliant Solution

      -
      +## Compliant Solution
      +
      +```python
       limit = my_function()
       for i in limit:
           ......
      -
      +``` + diff --git a/ecocode-rules-specifications/src/main/rules/EC7/python/EC7.asciidoc b/ecocode-rules-specifications/src/main/rules/EC7/python/EC7.asciidoc index dba3dd847..4ca4240e5 100644 --- a/ecocode-rules-specifications/src/main/rules/EC7/python/EC7.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC7/python/EC7.asciidoc @@ -1,6 +1,8 @@ -

      Avoid using getters and setters in a class, as they increase unnecessary RAM memory usage.

      -

      Noncompliant Code Example

      -
      +Avoid using getters and setters in a class, as they increase unnecessary RAM memory usage.
      +
      +## Noncompliant Code Example
      +
      +```python
       class Client():
       
           def __init__(self, age):
      @@ -15,10 +17,11 @@ class Client():
       client = Client(25)
       client.get_age() # Getter inutile
       client.set_age(25) # Setter inutile
      +```
       
      -
      -

      Compliant Solution

      -
      +## Compliant Solution
      +
      +```python
       class Client():
       
           def __init__(self, age):
      @@ -33,4 +36,5 @@ class Client():
       client = Client(25)
       client.age # Récupérer l'attribut age
       client.age = 26 # Modifier l'attribut age
      -
      +``` + diff --git a/ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc b/ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc index 7c6588afb..7032eb960 100644 --- a/ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc @@ -1,41 +1,17 @@ -

      Executing SQL queries in loop induced unnecessary calculation by the cpu, RAM usage and network transfer.

      -

      Noncompliant Code Example

      -
      -    public void foo() {
      -        ...
      -        String baseQuery = "SELECT name FROM users where id = ";
      -
      -        for (int i = 0; i < 20; i++) {
      -
      -            String query  = baseQuery.concat("" + i);
      -            Statement st = conn.createStatement();
      -            ResultSet rs = st.executeQuery(query); // Noncompliant
      -
      -            // iterate through the java resultset
      -            while (rs.next()) {
      -                String name = rs.getString("name");
      -                System.out.println(name);
      -            }
      -            st.close();
      -        }
      -        ...
      -    }
      +Executing SQL queries in loop induced unnecessary calculation by the CPU, RAM usage and network transfer.
       
      -
      -

      Compliant Solution

      -
      +## Noncompliant Code Example
       
      -    public void foo() {
      -        ...
      -        String query = "SELECT name FROM users where id in (0 ";
      -        for (int i = 1; i < 20; i++) {
      +```java
      +public void foo() {
      +    // ...
      +    String baseQuery = "SELECT name FROM users where id = ";
       
      -            query  = baseQuery.concat("," + i);
      -        }
      +    for (int i = 0; i < 20; i++) {
       
      -        query  = baseQuery.concat(")");
      +        String query  = baseQuery.concat("" + i);
               Statement st = conn.createStatement();
      -        ResultSet rs = st.executeQuery(query); // compliant
      +        ResultSet rs = st.executeQuery(query); // Noncompliant
       
               // iterate through the java resultset
               while (rs.next()) {
      @@ -43,7 +19,32 @@
                   System.out.println(name);
               }
               st.close();
      -        ...
      -   }
      +    }
      +    // ...
      +}
      +```
      +
      +## Compliant Solution
       
      -
      +```java +public void foo() { + // ... + String query = "SELECT name FROM users where id in (0 "; + for (int i = 1; i < 20; i++) { + + query = baseQuery.concat("," + i); + } + + query = baseQuery.concat(")"); + Statement st = conn.createStatement(); + ResultSet rs = st.executeQuery(query); // compliant + + // iterate through the java resultset + while (rs.next()) { + String name = rs.getString("name"); + System.out.println(name); + } + st.close(); + // ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC72/php/1GB.etsdiff.csv new file mode 100644 index 000000000..b006091ac --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC72/php/1GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),73.907586,82.15627099999998 +Transfer (B),49526,221836 +Storage (B),637549572,637549572 diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/2GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC72/php/2GB.etsdiff.csv new file mode 100644 index 000000000..73f5bac22 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC72/php/2GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),159.4871645,169.746055 +Transfer (B),50385,228225 +Storage (B),1178614788,1178614788 diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/4GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC72/php/4GB.etsdiff.csv new file mode 100644 index 000000000..4c253ef72 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC72/php/4GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),395.7629349999999,404.37447649999996 +Transfer (B),51597,238884 +Storage (B),2357214212,2357214212 diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/8GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC72/php/8GB.etsdiff.csv new file mode 100644 index 000000000..2a518e5eb --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC72/php/8GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),992.128585,1005.4625534999999 +Transfer (B),52189,249499 +Storage (B),4685052932,4685052932 diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc b/ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc index 7973ec509..12fe0d7b7 100644 --- a/ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc @@ -1,349 +1,91 @@ -

      Executing SQL queries in loop induced unnecessary network transfert, calculation by the cpu and RAM usage.

      -

      Noncompliant Code Example

      -
      -    public function foo() {
      -        ...
      -        $baseQuery = "SELECT name FROM users where id = ";
      +Executing SQL queries in loop induced unnecessary network transfert, calculation by the cpu and RAM usage.
      +
      +## Noncompliant Code Example
      +
      +```php
      +public function foo() {
      +    ...
      +    $baseQuery = "SELECT name FROM users where id = ";
       
      -        for ($i = 0; $i < 20; ++$i) {
      +    for ($i = 0; $i < 20; ++$i) {
       
      -            $query = $baseQuery . $i;
      -            $connection = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
      -		        mysql_select_db($dbname) or die("Could not open the db '$dbname'");
      -            $result = mysql_query($this->Query);// Noncompliant
      +        $query = $baseQuery . $i;
      +        $connection = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
      +            mysql_select_db($dbname) or die("Could not open the db '$dbname'");
      +        $result = mysql_query($this->Query);// Noncompliant
       
      -            // iterate through the result
      -            ...
      -            mysql_close($connection);
      -        }
      +        // iterate through the result
               ...
      +        mysql_close($connection);
           }
      +    ...
      +}
      +```
       
      -
      -

      Compliant Solution

      -
      +## Compliant Solution
       
      -    public function foo() {
      -        ...
      -        $query = "SELECT name FROM users where id in (";
      +```php
      +public function foo() {
      +    ...
      +    $query = "SELECT name FROM users where id in (";
       
      -        for ($i = 0; $i < 20; ++$i) {
      -            $query .= ',' . $i;
      -        }
      -        $query .= ')';
      +    for ($i = 0; $i < 20; ++$i) {
      +        $query .= ',' . $i;
      +    }
      +    $query .= ')';
       
      -        $connection = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
      -        mysql_select_db($dbname) or die("Could not open the db '$dbname'");
      -        $result = mysql_query($this->Query); // compliant
      +    $connection = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
      +    mysql_select_db($dbname) or die("Could not open the db '$dbname'");
      +    $result = mysql_query($this->Query); // compliant
       
      -        // iterate through the result
      -        ...
      -        mysql_close($connection);
      -   }
      +    // iterate through the result
      +    ...
      +    mysql_close($connection);
      +}
      +```
      +
      +include::../../etsdiff-methodology.asciidoc[]
      +
      +## Case for a 1GB database:
      +
      +image::https://live.staticflickr.com/65535/52622813465_9c453a43b1_w.jpg[ETSdiff percent comparison" style="padding: 1rem;]
      +
      +[format=csv,cols="1h,1,1"]
      +|===
      +Source of impacts,Compliant,Non-compliant
      +
      +include::1GB.etsdiff.csv[]
      +|===
      +
      +## Case for a 2GB database:
      +
      +image::https://live.staticflickr.com/65535/52622862388_720fd219ba_o.png[ETSdiff percent comparison" style="padding: 1rem;]
      +
      +[format=csv,cols="1h,1,1"]
      +|===
      +Source of impacts,Compliant,Non-compliant
      +
      +include::2GB.etsdiff.csv[]
      +|===
      +
      +## Case for a 4GB database:
      +
      +image::https://live.staticflickr.com/65535/52622814395_f8aab7a5c0_o.png[ETSdiff percent comparison" style="padding: 1rem;]
       
      -
      +[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant -

      The three sources of impacts of a code identified are:

      - - Energy (measured in joules) -
      - Transfer (measured in Bytes) -
      - Storage (measured in Bytes)
      -
      The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. -
      The ETSdiff tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). -
      The results generated by ETSdiff must help define the interest of the rule reported by Sonarqube in the context of the code analyzed. -
      +include::4GB.etsdiff.csv[] +|=== -

      Case for a 1GB database:

      -
      - ETSdiff percent comparison -
      -

      Total:

      - - - - - - - - - - - - - - - - - - - - - - - -
      -
      -
      Compliant
      -
      -
      -
      -
      Non-compliant
      -
      -
      -
      -
      Energy
      -
      -
      -
      -
      73.907586
      -
      -
      -
      -
      82.15627099999998
      -
      -
      -
      -
      Transfer
      -
      -
      -
      -
      49526
      -
      -
      -
      -
      221836
      -
      -
      -
      -
      Storage
      -
      -
      -
      -
      637549572
      -
      -
      -
      -
      637549572
      -
      -
      +## Case for a 8GB database: -

      Case for a 2GB database:

      -
      - ETSdiff percent comparison -
      -

      Total:

      - - - - - - - - - - - - - - - - - - - - - - - -
      -
      -
      Compliant
      -
      -
      -
      -
      Non-compliant
      -
      -
      -
      -
      Energy
      -
      -
      -
      -
      159.4871645
      -
      -
      -
      -
      169.746055
      -
      -
      -
      -
      Transfer
      -
      -
      -
      -
      50385
      -
      -
      -
      -
      228225
      -
      -
      -
      -
      Storage
      -
      -
      -
      -
      1178614788
      -
      -
      -
      -
      1178614788
      -
      -
      +image::https://live.staticflickr.com/65535/52622635779_f1c5d9660e_o.png[ETSdiff percent comparison" style="padding: 1rem;] -

      Case for a 4GB database:

      -
      - ETSdiff percent comparison -
      -

      Total:

      - - - - - - - - - - - - - - - - - - - - - - - -
      -
      -
      Compliant
      -
      -
      -
      -
      Non-compliant
      -
      -
      -
      -
      Energy
      -
      -
      -
      -
      395.7629349999999
      -
      -
      -
      -
      404.37447649999996
      -
      -
      -
      -
      Transfer
      -
      -
      -
      -
      51597
      -
      -
      -
      -
      238884
      -
      -
      -
      -
      Storage
      -
      -
      -
      -
      2357214212
      -
      -
      -
      -
      2357214212
      -
      -
      +[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant -

      Case for a 8GB database:

      -
      - ETSdiff percent comparison -
      -

      Total:

      - - - - - - - - - - - - - - - - - - - - - - - -
      -
      -
      Compliant
      -
      -
      -
      -
      Non-compliant
      -
      -
      -
      -
      Energy
      -
      -
      -
      -
      992.128585
      -
      -
      -
      -
      1005.4625534999999
      -
      -
      -
      -
      Transfer
      -
      -
      -
      -
      52189
      -
      -
      -
      -
      249499
      -
      -
      -
      -
      Storage
      -
      -
      -
      -
      4685052932
      -
      -
      -
      -
      4685052932
      -
      -
      \ No newline at end of file +include::8GB.etsdiff.csv[] +|=== diff --git a/ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc b/ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc index 2323c02f5..ae85dfe3e 100644 --- a/ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc @@ -1,21 +1,23 @@ -

      Executing SQL queries in loop induced unnecessary calculation by the cpu, RAM usage and network transfer.

      -

      Noncompliant Code Example

      -
      -    def foo():
      -        ...
      -        results = []
      -        for id in range(20):
      -          results.append(cursor.execute("SELECT name FROM users where id = ?", (id)).fetchone()) # Noncompliant {{Avoid performing SQL queries within a loop}}
      -        ...
      -
      -

      Compliant Solution

      -
      +Executing SQL queries in loop induced unnecessary calculation by the CPU, RAM usage and network transfer.
       
      -    def foo():
      -        ...
      -        ids = range(20)
      -        results = cursor.execute("SELECT name FROM users where id IN ({0})".format(', '.join("?" * len(ids))), ids).fetchmany() # Compliant
      -        ...
      -   }
      +## Noncompliant Code Example
       
      -
      +```python +def foo(): + ... + results = [] + for id in range(20): + results.append(cursor.execute("SELECT name FROM users where id = ?", (id)).fetchone()) # Noncompliant {{Avoid performing SQL queries within a loop}} + ... +``` + +## Compliant Solution + +```python +def foo(): + ... + ids = range(20) + results = cursor.execute("SELECT name FROM users where id IN ({0})".format(', '.join("?" * len(ids))), ids).fetchmany() # Compliant + ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc b/ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc index 35ffbf7af..4f1299b18 100644 --- a/ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc @@ -1,21 +1,21 @@ -

      Database servers have to resolve schema fields when using asterisk symbol (*). Knowing and using the schema saves CPU cycles and network transfer.

      -

      Noncompliant Code Example

      -
      -    public void foo() {
      -        ...
      -        String baseQuery = "SELECT * FROM users"; // Noncompliant
      +Database servers have to resolve schema fields when using asterisk symbol (`*`). Knowing and using the schema saves CPU cycles and network transfer.
       
      -        ...
      -    }
      +## Noncompliant Code Example
       
      -
      -

      Compliant Solution

      -
      +```java
      +public void foo() {
      +    // ...
      +    String baseQuery = "SELECT * FROM users"; // Noncompliant
      +    // ...
      +}
      +```
       
      -    public void foo() {
      -        ...
      -        String query = "SELECT id, name, address FROM users ";
      -        ...
      -   }
      +## Compliant Solution
       
      -
      +```java +public void foo() { + // ... + String query = "SELECT id, name, address FROM users"; + // ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC74/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC74/php/1GB.etsdiff.csv new file mode 100644 index 000000000..06710e417 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC74/php/1GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),0.040610499999999994,0.065223 +Transfer (B),779232,2697937 +Storage (B),637548827,637548827 diff --git a/ecocode-rules-specifications/src/main/rules/EC74/php/EC74.asciidoc b/ecocode-rules-specifications/src/main/rules/EC74/php/EC74.asciidoc index de53be78e..ffb380dd5 100644 --- a/ecocode-rules-specifications/src/main/rules/EC74/php/EC74.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC74/php/EC74.asciidoc @@ -1,101 +1,34 @@ -

      Database servers have to resolve schema fields when using asterisk symbol (*). Knowing and using the schema saves CPU cycles and network transfer.

      -

      Noncompliant Code Example

      -
      -    public function foo() {
      -        ...
      -        $baseQuery = "SELECT * FROM users"; // Noncompliant
      +Database servers have to resolve schema fields when using asterisk symbol (`*`). Knowing and using the schema saves CPU cycles and network transfer.
       
      -        ...
      -    }
      -
      -

      Compliant Solution

      -
      -    public function foo() {
      -        ...
      -        $baseQuery = "SELECT id,name, address FROM users ";
      -        ...
      -   }
      -
      -

      The three sources of impacts of a code identified are:

      -- Energy (measured in joules) -
      - Transfer (measured in Bytes) -
      - Storage (measured in Bytes)
      -
      The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. -
      The ETSdiff tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). -
      The results generated by ETSdiff must help define the interest of the rule reported by Sonarqube in the context of the code analyzed. -
      +## Noncompliant Code Example -

      Case for a 1GB database:

      -
      - ETSdiff percent comparison -
      +```php +public function foo() { + ... + $baseQuery = "SELECT * FROM users"; // Noncompliant + ... +} +``` -

      Total:

      - - - - - - - - - - - - - - - - - - - - - - - -
      -
      -
      Compliant
      -
      -
      -
      -
      Non-compliant
      -
      -
      -
      -
      Energy
      -
      -
      -
      -
      0.040610499999999994
      -
      -
      -
      -
      0.065223
      -
      -
      -
      -
      Transfer
      -
      -
      -
      -
      779232
      -
      -
      -
      -
      2697937
      -
      -
      -
      -
      Storage
      -
      -
      -
      -
      637548827
      -
      -
      -
      -
      637548827
      -
      -
      +## Compliant Solution + +```php +public function foo() { + ... + $baseQuery = "SELECT id,name, address FROM users "; + ... +} +``` + +include::../../etsdiff-methodology.asciidoc[] + +## Case for a 1GB database: + +image::https://live.staticflickr.com/65535/52622636584_52938fcf7e_o.png[ETSdiff percent comparison] + +[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant + +include::1GB.etsdiff.csv[] +|=== diff --git a/ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc b/ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc index 35ffbf7af..3b9b41c0f 100644 --- a/ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc @@ -1,21 +1,21 @@ -

      Database servers have to resolve schema fields when using asterisk symbol (*). Knowing and using the schema saves CPU cycles and network transfer.

      -

      Noncompliant Code Example

      -
      -    public void foo() {
      -        ...
      -        String baseQuery = "SELECT * FROM users"; // Noncompliant
      +Database servers have to resolve schema fields when using asterisk symbol (`*`). Knowing and using the schema saves CPU cycles and network transfer.
       
      -        ...
      -    }
      +## Noncompliant Code Example
       
      -
      -

      Compliant Solution

      -
      +```python
      +public void foo() {
      +    ...
      +    String baseQuery = "SELECT * FROM users"; // Noncompliant
      +    ...
      +}
      +```
       
      -    public void foo() {
      -        ...
      -        String query = "SELECT id, name, address FROM users ";
      -        ...
      -   }
      +## Compliant Solution
       
      -
      +```python +public void foo() { + ... + String query = "SELECT id, name, address FROM users "; + ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC75/java/EC75.asciidoc b/ecocode-rules-specifications/src/main/rules/EC75/java/EC75.asciidoc index 67c1c1ccf..6cbc5ed2a 100644 --- a/ecocode-rules-specifications/src/main/rules/EC75/java/EC75.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC75/java/EC75.asciidoc @@ -1,41 +1,38 @@ -

      - Don't concatenate Strings in loop. User StringBuilder instead.
      - Strings are immutable so each time you concatenate a String, a new String is created. This is a waste of memory and CPU. -

      +Don't concatenate Strings in loop. Use `StringBuilder instead. -

      Noncompliant Code Example

      -
      +Strings are immutable so each time you concatenate a String, a new String is created. This is a waste of memory and CPU.
       
      -    public String concatenateStrings(String[] strings) {
      -        String result = "";
      +## Noncompliant Code Example
       
      -        for (String string : strings) {
      -            result += string; // Noncompliant
      -        }
      -        return result;
      +```java
      +public String concatenateStrings(String[] strings) {
      +    String result = "";
      +
      +    for (String string : strings) {
      +        result += string; // Noncompliant
           }
      +    return result;
      +}
       
      -    public String concatenateStrings2() {
      -        String result = "";
      +public String concatenateStrings2() {
      +    String result = "";
       
      -        for (int i = 0; i < 1000; ++i) {
      -            result += "another"; // Noncompliant
      -        }
      -        return result;
      +    for (int i = 0; i < 1000; ++i) {
      +        result += "another"; // Noncompliant
           }
      +    return result;
      +}
      +```
       
      -
      - -

      Compliant Solution

      -
      +## Compliant Solution
       
      -    public String concatenateStrings(String[] strings) {
      -        StringBuilder result = new StringBuilder();
      +```java
      +public String concatenateStrings(String[] strings) {
      +    StringBuilder result = new StringBuilder();
       
      -        for (String string : strings) {
      -            result.append(string);
      -        }
      -        return result.toString();
      +    for (String string : strings) {
      +        result.append(string);
           }
      -
      -
      + return result.toString(); +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC76/java/EC76.asciidoc b/ecocode-rules-specifications/src/main/rules/EC76/java/EC76.asciidoc index 608b0285b..f21e5298c 100644 --- a/ecocode-rules-specifications/src/main/rules/EC76/java/EC76.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC76/java/EC76.asciidoc @@ -1,38 +1,36 @@ -

      - Avoid usage of static collections.
      - If you want to use static collections make them final and create for example a singleton if needed containing the collections.
      - The static fields are more complicated for the Garbage Collector to manage and can lead to memory leaks. -

      - -

      Noncompliant Code Example

      -
      -
      -    /**
      -     * Not compliant
      -     */
      -    public class AvoidUsageOfStaticCollections {
      -        public static final List<> LIST = new ArrayList<>();
      -        public static final Set<> SET = new HashSet<>();
      -        public static final Map<> MAP = new HashMap<>();
      -    }
      +Avoid usage of static collections.
       
      -
      +If you want to use static collections make them final and create for example a singleton if needed containing the collections. -

      Compliant Solution

      -
      +The static fields are more complicated for the Garbage Collector to manage and can lead to memory leaks.
       
      -    /**
      -     * Compliant
      -     */
      -    public class GoodUsageOfStaticCollections {
      -        public static volatile GoodUsageOfStaticCollections INSTANCE = new GoodUsageOfStaticCollections();
      +## Noncompliant Code Example
       
      -        public final List<> LIST = new ArrayList<>();
      -        public final Set<> SET = new HashSet<>();
      -        public final Map<> MAP = new HashMap<>();
      +```java
      +/**
      + * Not compliant
      + */
      +public class AvoidUsageOfStaticCollections {
      +    public static final List<> LIST = new ArrayList<>();
      +    public static final Set<> SET = new HashSet<>();
      +    public static final Map<> MAP = new HashMap<>();
      +}
      +```
       
      -        private GoodUsageOfStaticCollections() {
      -        }
      -    }
      +## Compliant Solution
      +
      +```java
      +/**
      + * Compliant
      + */
      +public class GoodUsageOfStaticCollections {
      +    public static volatile GoodUsageOfStaticCollections INSTANCE = new GoodUsageOfStaticCollections();
       
      -
      \ No newline at end of file + public final List<> LIST = new ArrayList<>(); + public final Set<> SET = new HashSet<>(); + public final Map<> MAP = new HashMap<>(); + + private GoodUsageOfStaticCollections() { + } +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc b/ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc index f0aed4f4f..188b8f648 100644 --- a/ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc @@ -1,67 +1,53 @@ -

      - Avoid using Pattern.compile() in a non-static context. - This operation requires a significant amount of computational power, Using a single match saves CPU cycles and RAM consumption. -

      +Avoid using `Pattern.compile()` in a non-static context. +This operation requires a significant amount of computational power, Using a single match saves CPU cycles and RAM consumption. -

      Noncompliant Code Example

      -
      -
      -    public class AvoidRegexPatternNotStatic {
      -
      -        public boolean foo() {
      -            final Pattern pattern = Pattern.compile("foo"); // Noncompliant
      -            return pattern.matcher("foo").find();
      -        }
      +## Noncompliant Code Example
       
      +```java
      +public class AvoidRegexPatternNotStatic {
      +    public boolean foo() {
      +        final Pattern pattern = Pattern.compile("foo"); // Noncompliant
      +        return pattern.matcher("foo").find();
           }
      +}
      +```
       
      -
      - -

      Compliant Solution N°1

      -
      -
      -    public class ValidRegexPattern {
      +## Compliant Solution N°1
       
      -        private static final Pattern pattern = Pattern.compile("foo"); // Compliant
      -
      -        public boolean foo() {
      -            return pattern.matcher("foo").find();
      -        }
      +```java
      +public class ValidRegexPattern {
      +    private static final Pattern pattern = Pattern.compile("foo"); // Compliant
       
      +    public boolean foo() {
      +        return pattern.matcher("foo").find();
           }
      +}
      +```
       
      -
      - -

      Compliant Solution N°2

      -
      -
      -    public class ValidRegexPattern2 {
      +## Compliant Solution N°2
       
      -        private final Pattern pattern = Pattern.compile("foo"); // Compliant
      -
      -        public boolean foo() {
      -            return pattern.matcher("foo").find();
      -        }
      +```java
      +public class ValidRegexPattern2 {
      +    private final Pattern pattern = Pattern.compile("foo"); // Compliant
       
      +    public boolean foo() {
      +        return pattern.matcher("foo").find();
           }
      +}
      +```
       
      -
      - -

      Compliant Solution N°3

      -
      -
      -    public class ValidRegexPattern3 {
      +## Compliant Solution N°3
       
      -        private final Pattern pattern;
      -
      -        public ValidRegexPattern3() {
      -            pattern = Pattern.compile("foo"); // Compliant
      -        }
      -
      -        public boolean foo() {
      -            return pattern.matcher("foo").find();
      -        }
      +```java
      +public class ValidRegexPattern3 {
      +    private final Pattern pattern;
       
      +    public ValidRegexPattern3() {
      +        pattern = Pattern.compile("foo"); // Compliant
           }
       
      -
      + public boolean foo() { + return pattern.matcher("foo").find(); + } +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC78/java/EC78.asciidoc b/ecocode-rules-specifications/src/main/rules/EC78/java/EC78.asciidoc index 2b0c687b0..3153a8742 100644 --- a/ecocode-rules-specifications/src/main/rules/EC78/java/EC78.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC78/java/EC78.asciidoc @@ -1,30 +1,34 @@ -

      Don't set const parameter in batch update => Put its in query. Creating this parameter and destroying it consumes CPU cycles and RAM unnecessarily.

      -

      Noncompliant Code Example

      -
      -    public void foo() {
      -    	...
      -    	String query = "insert into mytable values(?,?,?)";
      -        ...
      -        for(DummyClass o : list) {
      -			stmt.setInt(1, 123);  // Noncompliant
      -			stmt.setString(2, o.getName());
      -			stmt.setDouble(3, o.getPrice());
      -			stmt.addBatch();
      -		}
      -        ...
      +Don't set a constant parameter in batch update. Instead, put it in query. Creating this parameter and destroying it consumes CPU cycles and RAM unnecessarily.
      +
      +## Noncompliant Code Example
      +
      +```java
      +public void foo() {
      +    // ...
      +    String query = "insert into mytable values(?,?,?)";
      +    // ...
      +    for(DummyClass o : list) {
      +        stmt.setInt(1, 123);  // Noncompliant
      +        stmt.setString(2, o.getName());
      +        stmt.setDouble(3, o.getPrice());
      +        stmt.addBatch();
           }
      -
      -

      Compliant Solution

      -
      -    public void foo() {
      -    	...
      -    	String query = "insert into mytable values(123,?,?)";
      -        ...
      -        for(DummyClass o : list) {
      -			stmt.setString(1, o.getName());
      -			stmt.setDouble(2, o.getPrice());
      -			stmt.addBatch();
      -		}
      -        ...
      +    // ...
      +}
      +```
      +
      +## Compliant Solution
      +
      +```java
      +public void foo() {
      +    // ...
      +    String query = "insert into mytable values(123,?,?)";
      +    // ...
      +    for(DummyClass o : list) {
      +        stmt.setString(1, o.getName());
      +        stmt.setDouble(2, o.getPrice());
      +        stmt.addBatch();
           }
      -
      + // ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC79/java/EC79.asciidoc b/ecocode-rules-specifications/src/main/rules/EC79/java/EC79.asciidoc index f8801ef21..ef8bc2156 100644 --- a/ecocode-rules-specifications/src/main/rules/EC79/java/EC79.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC79/java/EC79.asciidoc @@ -1,24 +1,28 @@ -

      try-with-resources Statement needs to be implemented for any object that implements the AutoCloseable interface, it save computer resources.

      -

      Noncompliant Code Example

      -
      -    private static void printFileJava7() throws IOException {
      -        FileInputStream input = new FileInputStream("file.txt");
      +Use `try-with-resources` statement for any object that implements the `AutoCloseable` interface, it save computer resources.
      +
      +## Noncompliant Code Example
      +
      +```java
      +private static void printFileJava7() throws IOException {
      +    FileInputStream input = new FileInputStream("file.txt");
      +    int data = input.read();
      +    while(data != -1){
      +        System.out.print((char) data);
      +        data = input.read();
      +    }
      +}
      +```
      +
      +## Compliant Solution
      +
      +```java
      +private static void printFileJava7() throws IOException {
      +    try(FileInputStream input = new FileInputStream("file.txt")) {
               int data = input.read();
               while(data != -1){
                   System.out.print((char) data);
                   data = input.read();
               }
           }
      -
      -

      Compliant Solution

      -
      -    private static void printFileJava7() throws IOException {
      -        try(FileInputStream input = new FileInputStream("file.txt")) {
      -            int data = input.read();
      -            while(data != -1){
      -                System.out.print((char) data);
      -                data = input.read();
      -            }
      -        }
      -    }
      -
      +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/etsdiff-methodology.asciidoc b/ecocode-rules-specifications/src/main/rules/etsdiff-methodology.asciidoc new file mode 100644 index 000000000..3239fa7d4 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/etsdiff-methodology.asciidoc @@ -0,0 +1,11 @@ +## The three sources of impacts of a code identified are: + +- Energy: measured in joules (J) +- Transfer: measured in Bytes (B) +- Storage: measured in Bytes (B) + +The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. + +The _ETSdiff_ tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). + +The results generated by _ETSdiff_ must help define the interest of the rule reported by _SonarQube_ in the context of the code analyzed. From 7d3683b60e916cd1c8f883ee4fb9852892b2ea91 Mon Sep 17 00:00:00 2001 From: jycr Date: Mon, 10 Jul 2023 00:14:31 +0200 Subject: [PATCH 112/170] feat(rule): Add rules of green-code-initiative/ecoCode-javascript#14 --- ecocode-rules-specifications/pom.xml | 38 ++++++++++ .../src/main/assembly/js.xml | 18 +++++ .../src/main/assembly/ts.xml | 18 +++++ .../src/main/rules/EC11/EC11.json | 19 +++++ .../src/main/rules/EC11/js/EC11.asciidoc | 20 ++++++ .../src/main/rules/EC12/EC12.json | 19 +++++ .../src/main/rules/EC12/js/EC12.asciidoc | 33 +++++++++ .../src/main/rules/EC13/EC13.json | 19 +++++ .../src/main/rules/EC13/ts/EC13.asciidoc | 31 +++++++++ .../src/main/rules/EC8/EC8.json | 19 +++++ .../src/main/rules/EC8/js/EC8.asciidoc | 43 ++++++++++++ .../src/main/rules/EC9/EC9.json | 19 +++++ .../src/main/rules/EC9/js/EC9.asciidoc | 69 +++++++++++++++++++ 13 files changed, 365 insertions(+) create mode 100644 ecocode-rules-specifications/src/main/assembly/js.xml create mode 100644 ecocode-rules-specifications/src/main/assembly/ts.xml create mode 100644 ecocode-rules-specifications/src/main/rules/EC11/EC11.json create mode 100644 ecocode-rules-specifications/src/main/rules/EC11/js/EC11.asciidoc create mode 100644 ecocode-rules-specifications/src/main/rules/EC12/EC12.json create mode 100644 ecocode-rules-specifications/src/main/rules/EC12/js/EC12.asciidoc create mode 100644 ecocode-rules-specifications/src/main/rules/EC13/EC13.json create mode 100644 ecocode-rules-specifications/src/main/rules/EC13/ts/EC13.asciidoc create mode 100644 ecocode-rules-specifications/src/main/rules/EC8/EC8.json create mode 100644 ecocode-rules-specifications/src/main/rules/EC8/js/EC8.asciidoc create mode 100644 ecocode-rules-specifications/src/main/rules/EC9/EC9.json create mode 100644 ecocode-rules-specifications/src/main/rules/EC9/js/EC9.asciidoc diff --git a/ecocode-rules-specifications/pom.xml b/ecocode-rules-specifications/pom.xml index 30e3f07ce..6dee12f0d 100644 --- a/ecocode-rules-specifications/pom.xml +++ b/ecocode-rules-specifications/pom.xml @@ -133,6 +133,20 @@ + + + + + + + + + + + + + + @@ -190,6 +204,30 @@ + + assembly-js + prepare-package + + single + + + + ${project.basedir}/src/main/assembly/js.xml + + + + + assembly-ts + prepare-package + + single + + + + ${project.basedir}/src/main/assembly/ts.xml + + + true diff --git a/ecocode-rules-specifications/src/main/assembly/js.xml b/ecocode-rules-specifications/src/main/assembly/js.xml new file mode 100644 index 000000000..d5d72ca1e --- /dev/null +++ b/ecocode-rules-specifications/src/main/assembly/js.xml @@ -0,0 +1,18 @@ + + js + + jar + + false + + + ${project.build.outputDirectory} + + io/ecocode/rules/js/*.* + + + + + diff --git a/ecocode-rules-specifications/src/main/assembly/ts.xml b/ecocode-rules-specifications/src/main/assembly/ts.xml new file mode 100644 index 000000000..ec0100661 --- /dev/null +++ b/ecocode-rules-specifications/src/main/assembly/ts.xml @@ -0,0 +1,18 @@ + + ts + + jar + + false + + + ${project.build.outputDirectory} + + io/ecocode/rules/ts/*.* + + + + + diff --git a/ecocode-rules-specifications/src/main/rules/EC11/EC11.json b/ecocode-rules-specifications/src/main/rules/EC11/EC11.json new file mode 100644 index 000000000..878a34665 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC11/EC11.json @@ -0,0 +1,19 @@ +{ + "title": "Disallow multiple access of same DOM element.", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "eco-design", + "performance", + "ecocode" + ], + "defaultSeverity": "Major", + "compatibleLanguages": [ + "JAVASCRIPT", + "TYPESCRIPT" + ] +} diff --git a/ecocode-rules-specifications/src/main/rules/EC11/js/EC11.asciidoc b/ecocode-rules-specifications/src/main/rules/EC11/js/EC11.asciidoc new file mode 100644 index 000000000..b5a2a8649 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC11/js/EC11.asciidoc @@ -0,0 +1,20 @@ +## Rule details + +This rule aims to reduce DOM access assigning its object to variable when access multiple time. It saves CPU cycles. + +## Examples + +Examples of **incorrect** code for this rule: + +```js +var el1 = document.getElementById("block1").test1; +var el2 = document.getElementById("block1").test2; +``` + +Examples of **correct** code for this rule: + +```js +var blockElement = document.getElementById("block1"); +var el1 = blockElement.test1; +var el2 = blockElement.test2; +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC12/EC12.json b/ecocode-rules-specifications/src/main/rules/EC12/EC12.json new file mode 100644 index 000000000..67c6010cf --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC12/EC12.json @@ -0,0 +1,19 @@ +{ + "title": "Disallow multiple style changes at once.", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "10min" + }, + "tags": [ + "eco-design", + "performance", + "ecocode" + ], + "defaultSeverity": "Major", + "compatibleLanguages": [ + "JAVASCRIPT", + "TYPESCRIPT" + ] +} diff --git a/ecocode-rules-specifications/src/main/rules/EC12/js/EC12.asciidoc b/ecocode-rules-specifications/src/main/rules/EC12/js/EC12.asciidoc new file mode 100644 index 000000000..5bd836997 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC12/js/EC12.asciidoc @@ -0,0 +1,33 @@ +## Rule Details + +This rule aims to disallow batching multiple style changes at once. + +To limit the number of repaint/reflow, it is advised to batch style modifications by adding a class containing all style changes that will generate a unique reflow. + +## Examples + +Examples of **non-compliant** code for this rule: + +```html + +``` + +Examples of **compliant** code for this rule: + +```html + + + +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC13/EC13.json b/ecocode-rules-specifications/src/main/rules/EC13/EC13.json new file mode 100644 index 000000000..6ff60b4fa --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC13/EC13.json @@ -0,0 +1,19 @@ +{ + "title": "Prefer API collections with pagination.", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "30min" + }, + "tags": [ + "eco-design", + "performance", + "ecocode" + ], + "defaultSeverity": "Minor", + "compatibleLanguages": [ + "JAVASCRIPT", + "TYPESCRIPT" + ] +} diff --git a/ecocode-rules-specifications/src/main/rules/EC13/ts/EC13.asciidoc b/ecocode-rules-specifications/src/main/rules/EC13/ts/EC13.asciidoc new file mode 100644 index 000000000..abc58bf6c --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC13/ts/EC13.asciidoc @@ -0,0 +1,31 @@ +## Rule details + +This rule aims to reduce the size and thus the network weight of API returns that may contain many elements. This rule is built for the https://nestjs.com[NestJS framework] but can work with a controller `@Controller()` and a decorated method `@Get()`. + +## Examples + +Examples of **non-compliant** code for this rule: + +```typescript +@Controller() +class Test { + @Get() + public find(): Promise {} +} +``` + +Examples of **compliant** code for this rule: + +```typescript +interface Pagination { + items: string[]; + currentPage: number; + totalPages: number; +} + +@Controller() +class Test { + @Get() + public find(): Promise {} +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC8/EC8.json b/ecocode-rules-specifications/src/main/rules/EC8/EC8.json new file mode 100644 index 000000000..232f1ce0a --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC8/EC8.json @@ -0,0 +1,19 @@ +{ + "title": "Avoid using high accuracy geolocation in web applications.", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "5min" + }, + "tags": [ + "eco-design", + "performance", + "ecocode" + ], + "defaultSeverity": "Major", + "compatibleLanguages": [ + "JAVASCRIPT", + "TYPESCRIPT" + ] +} diff --git a/ecocode-rules-specifications/src/main/rules/EC8/js/EC8.asciidoc b/ecocode-rules-specifications/src/main/rules/EC8/js/EC8.asciidoc new file mode 100644 index 000000000..7528b2bb2 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC8/js/EC8.asciidoc @@ -0,0 +1,43 @@ +## Rule details + +This rule aims at reducing CPU consumption by telling the device to use a less accurate yet more eco-friendly geolocation, when geolocation API is used. + +## Examples + +Examples of **non-compliant** code for this rule: + +```js +var options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }; +function success(pos) { + console.log(pos.coords); +} + +function error(err) { + console.warn(err); +} + +navigator.geolocation.getCurrentPosition(success, error, options); +``` + +Examples of **compliant** code for this rule: + +```js +// enableHighAccuracy is false by default, so not declaring it is correct +function success(pos) { + console.log(pos); +} +navigator.geolocation.getCurrentPosition(success); +``` + +```js +var options = { enableHighAccuracy: false, timeout: 5000, maximumAge: 0 }; +function success(pos) { + console.log(pos.coords); +} + +function error(err) { + console.warn(err); +} + +navigator.geolocation.getCurrentPosition(success, error, options); +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC9/EC9.json b/ecocode-rules-specifications/src/main/rules/EC9/EC9.json new file mode 100644 index 000000000..99e524b50 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC9/EC9.json @@ -0,0 +1,19 @@ +{ + "title": "Should not import all from library", + "type": "CODE_SMELL", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "15min" + }, + "tags": [ + "eco-design", + "performance", + "ecocode" + ], + "defaultSeverity": "Major", + "compatibleLanguages": [ + "JAVASCRIPT", + "TYPESCRIPT" + ] +} diff --git a/ecocode-rules-specifications/src/main/rules/EC9/js/EC9.asciidoc b/ecocode-rules-specifications/src/main/rules/EC9/js/EC9.asciidoc new file mode 100644 index 000000000..c6be22d50 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC9/js/EC9.asciidoc @@ -0,0 +1,69 @@ +## Rule details + +This rule aims to reduce weight of programs by using only needed modules. Many libraries export only one module by default, but some of them are exporting ES modules or submodules. We should use them to select more precisly needed modules and avoid unnecessarily overloading files weight. + +*Example with the well-known https://lodash.com/[lodash] library, if you only need +`isEmpty` method.* + + +|=== +|Full lodash library |Only `isEmpty` method + +a|index.js - 531.46 KB + +* node_modules/lodash - 531.35 KB +** lodash.js - 531.35 KB + +a|index.js - 24.42 KB + +* node_modules/lodash - 24.31 KB +** isEmpty - 1.95 KB +** _nodeUtil.js - 995 B +** isArrayLike.js - 830 B +** ... + +|=== + +## Options + +You can externally add your own libraries to be checked. To add your own libraries you need to modify your .eslintrc.js by adding the following rule configuration: + +```js +module.exports = { + ...yourConf, + rules: { + "no-import-all-from-library": [ + "warn", + { + notAllowedLibraries: ["some-lib"], // will check for -> import someLib from "some-lib" + importByNamespaceNotAllowedLibraries: ["some-other-lib"], // will check for -> import * as someOtherLib from "some-other-lib" + }, + ], + }, +}; +``` + +## Examples + +Examples of **non-compliant** code for this rule: + +```js +// Example with lodash +import lodash from "lodash"; +import { isEmpty } from "lodash"; +import * as lodash from "lodash"; + +// Example with underscore +import _ from "underscore"; +``` + +Examples of **compliant** code for this rule: + +```js +// Example with lodash (uses submodules) +import isEmpty from "lodash/isEmpty"; +import intersect from "lodash/intersect"; + +// Example with underscore (uses esm modules) +import map from "underscore/modules/map.js"; +``` From 523686d33b296847da2061b0236650a23e42c930 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 11 Jul 2023 10:59:39 +0700 Subject: [PATCH 113/170] update readme.md with new release version --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index c050991eb..7b34c611b 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ Ready to use binaries are available [from GitHub](https://github.com/green-code- | 1.0.+ | SonarQube 9.4.+ LTS to 9.9 | | 1.1.+ | SonarQube 9.4.+ LTS to 9.9 | | 1.2.+ | SonarQube 9.4.+ LTS to 10.0 | +| 1.3.+ | SonarQube 9.4.+ LTS to 10.0 | ☕ Plugin Java part compatibility ------------------ @@ -96,6 +97,7 @@ Ready to use binaries are available [from GitHub](https://github.com/green-code- | 1.0.+ | 11 / 17 | | 1.1.+ | 11 / 17 | | 1.2.+ | 11 / 17 | +| 1.3.+ | 11 / 17 | 🤝 Contribution --------------- From 449a3ff91ea154b9c3c3f9d409463eb4a72692db Mon Sep 17 00:00:00 2001 From: utarwyn Date: Thu, 13 Jul 2023 21:31:03 +0200 Subject: [PATCH 114/170] Remove javascript-plugin --- .github/workflows/manual_release.yml | 21 --- .github/workflows/tag_release.yml | 21 --- INSTALL.md | 3 - README.md | 4 +- docker-compose.yml | 3 - javascript-plugin/README.md | 22 --- javascript-plugin/pom.xml | 130 ------------------ .../javascript/JavaScriptPlugin.java | 28 ---- .../javascript/JavaScriptRulesDefinition.java | 40 ------ .../l10n/javascript/rules.json | 62 --------- .../javascript/JavaScriptPluginTest.java | 20 --- .../JavaScriptRulesDefinitionTest.java | 22 --- pom.xml | 11 -- 13 files changed, 1 insertion(+), 386 deletions(-) delete mode 100644 javascript-plugin/README.md delete mode 100644 javascript-plugin/pom.xml delete mode 100644 javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptPlugin.java delete mode 100644 javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinition.java delete mode 100644 javascript-plugin/src/main/resources/fr/greencodeinitiative/l10n/javascript/rules.json delete mode 100644 javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java delete mode 100644 javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinitionTest.java diff --git a/.github/workflows/manual_release.yml b/.github/workflows/manual_release.yml index 787a4400a..e3d225726 100644 --- a/.github/workflows/manual_release.yml +++ b/.github/workflows/manual_release.yml @@ -89,27 +89,6 @@ jobs: asset_path: lib/ecocode-java-plugin-${{ needs.build.outputs.last_tag }}.jar asset_name: ecocode-java-plugin-${{ needs.build.outputs.last_tag }}.jar asset_content_type: application/zip - upload-javascript: - name: Upload JavaScript Plugin - runs-on: ubuntu-latest - needs: build - steps: - - name: Import plugin JAR files - id: import_jar_files - uses: actions/download-artifact@v3 - with: - name: ecocode-plugins - path: lib - - name: Upload Release Asset - JavaScript Plugin - id: upload-release-asset - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{needs.build.outputs.upload_url}} - asset_path: lib/ecocode-javascript-plugin-${{ needs.build.outputs.last_tag }}.jar - asset_name: ecocode-javascript-plugin-${{ needs.build.outputs.last_tag }}.jar - asset_content_type: application/zip upload-php: name: Upload PHP Plugin runs-on: ubuntu-latest diff --git a/.github/workflows/tag_release.yml b/.github/workflows/tag_release.yml index 0d2f3d605..ff213b10c 100644 --- a/.github/workflows/tag_release.yml +++ b/.github/workflows/tag_release.yml @@ -69,27 +69,6 @@ jobs: asset_path: lib/ecocode-java-plugin-${{ github.ref_name }}.jar asset_name: ecocode-java-plugin-${{ github.ref_name }}.jar asset_content_type: application/zip - upload-javascript: - name: Upload JavaScript Plugin - runs-on: ubuntu-latest - needs: build - steps: - - name: Import plugin JAR files - id: import_jar_files - uses: actions/download-artifact@v3 - with: - name: ecocode-plugins - path: lib - - name: Upload Release Asset - JavaScript Plugin - id: upload-release-asset - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{needs.build.outputs.upload_url}} - asset_path: lib/ecocode-javascript-plugin-${{ github.ref_name }}.jar - asset_name: ecocode-javascript-plugin-${{ github.ref_name }}.jar - asset_content_type: application/zip upload-php: name: Upload PHP Plugin runs-on: ubuntu-latest diff --git a/INSTALL.md b/INSTALL.md index 716f51d09..46d6673fb 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -23,8 +23,6 @@ ecoCode # Root directory | +--java-plugin # JAVA | -+--javascript-plugin # JavaScript -| +--php-plugin # PHP | +--python-plugin # Python @@ -38,6 +36,5 @@ Plugin-specific guides ---------------------- - [Java how-to](java-plugin/README.md) -- [JavaScript how-to](javascript-plugin/README.md) - [Python how-to](python-plugin/README.md) - [PHP how-to](php-plugin/README.md) diff --git a/README.md b/README.md index 7b34c611b..7a7be356b 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ refer to the contribution section. 4 technologies are supported by ecoCode right now: - [Java](java-plugin/) -- [JavaScript](javascript-plugin/) +- [JavaScript](https://github.com/green-code-initiative/ecoCode-javascript) - [PHP](php-plugin/) - [Python](python-plugin/) @@ -48,8 +48,6 @@ For example, you’ll be able to access of all your `for` loop, to explore conte To better understand AST structure, you can use the [AST Explorer](https://astexplorer.net/). -JavaScript plugin works differently because it does not use AST. [More information here](javascript-plugin/README.md) - 🚀 Getting Started ------------------ diff --git a/docker-compose.yml b/docker-compose.yml index 76f87d1ce..6e1351794 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -18,9 +18,6 @@ services: - type: bind source: ./java-plugin/target/ecocode-java-plugin-1.3.1-SNAPSHOT.jar target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.3.1-SNAPSHOT.jar - - type: bind - source: ./javascript-plugin/target/ecocode-javascript-plugin-1.3.1-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-javascript-plugin-1.3.1-SNAPSHOT.jar - type: bind source: ./php-plugin/target/ecocode-php-plugin-1.3.1-SNAPSHOT.jar target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.3.1-SNAPSHOT.jar diff --git a/javascript-plugin/README.md b/javascript-plugin/README.md deleted file mode 100644 index b6095a6ea..000000000 --- a/javascript-plugin/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# ecoCode JavaScript plugin - -This plugin behaves differently from the others in the ecoCode project. Since version 8.9 of SonarQube, it is no longer -possible to use an AST to implement a -rule, [as explained here](https://github.com/SonarSource/sonar-custom-rules-examples/tree/master/javascript-custom-rules). -In compliance with the SonarSource decision, the ecoCode project uses ESLint to implement the custom rules. - -Thus, the plugin does not implement any rules. Its purpose is to import the result of the ESLint analysis of the -project made with the ecoCode linter, with the complete documentation of each rule. In this context, the rules are -considered by SonarQube as external: they do not appear in the list of rules but are reported as real rules during the -analysis ([click to learn more](https://docs.sonarqube.org/latest/analyzing-source-code/importing-external-issues/importing-third-party-issues/)). - -🚀 Getting Started ------------------- - -The installation is not much more complicated than another ecoCode plugin. In addition to the Sonar plugin, you will -need to install the ESLint plugin in your JavaScript/TypeScript project to be analyzed: - -- Install the SonarQube plugin as described in the [ecoCode README](../README.md#-getting-started). -- Install the ESLint plugin into your project as described - in [ESLint project README](https://github.com/green-code-initiative/ecoCode-linter/blob/main/eslint-plugin/README.md#installation).\ - This guide also explains how to configure ESLint to import results into SonarQube. diff --git a/javascript-plugin/pom.xml b/javascript-plugin/pom.xml deleted file mode 100644 index d9d7e5519..000000000 --- a/javascript-plugin/pom.xml +++ /dev/null @@ -1,130 +0,0 @@ - - - 4.0.0 - - - io.ecocode - ecocode-parent - 1.3.1-SNAPSHOT - - - ecocode-javascript-plugin - sonar-plugin - - ecoCode - JavaScript language - Provides rules to reduce the environmental footprint of your JavaScript programs - https://github.com/green-code-initiative/ecoCode/tree/main/javascript-plugin - - - - - org.sonarsource.javascript - sonar-javascript-plugin - sonar-plugin - - - - org.sonarsource.sonarqube - sonar-plugin-api - - - - org.sonarsource.analyzer-commons - sonar-analyzer-commons - - - - org.junit.jupiter - junit-jupiter - test - - - - org.assertj - assertj-core - test - - - - org.mockito - mockito-junit-jupiter - test - - - - - - - - org.sonarsource.sonar-packaging-maven-plugin - sonar-packaging-maven-plugin - true - - ecocodejavascript - ${project.name} - fr.greencodeinitiative.javascript.JavaScriptPlugin - true - ${sonarqube.version} - ${java.version} - - - - - org.apache.maven.plugins - maven-shade-plugin - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-bundle - package - - copy - - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - jar - true - - - ../lib - - - - - - org.jacoco - jacoco-maven-plugin - - file - false - - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - - - - diff --git a/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptPlugin.java b/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptPlugin.java deleted file mode 100644 index 66dba696c..000000000 --- a/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptPlugin.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2023 Green Code Initiative - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.javascript; - -import org.sonar.api.Plugin; - -public class JavaScriptPlugin implements Plugin { - - @Override - public void define(Context context) { - context.addExtension(JavaScriptRulesDefinition.class); - } - -} diff --git a/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinition.java b/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinition.java deleted file mode 100644 index f13409ce4..000000000 --- a/javascript-plugin/src/main/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinition.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2023 Green Code Initiative - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.javascript; - -import org.sonar.api.server.rule.RulesDefinition; -import org.sonarsource.analyzer.commons.ExternalRuleLoader; - -public class JavaScriptRulesDefinition implements RulesDefinition { - - private static final String LANGUAGE = "js"; - - /* - As we integrate our rules using SonarJS, these values should remain to "eslint_repo" and "ESLint" in order to import them correctly - see: https://github.com/green-code-initiative/ecoCode/pull/79#discussion_r1137797583 - */ - private static final String LINTER_KEY = "eslint_repo"; - private static final String LINTER_NAME = "ESLint"; - private static final String METADATA_PATH = "fr/greencodeinitiative/l10n/javascript/rules.json"; - - @Override - public void define(Context context) { - new ExternalRuleLoader(LINTER_KEY, LINTER_NAME, METADATA_PATH, LANGUAGE) - .createExternalRuleRepository(context); - } - -} diff --git a/javascript-plugin/src/main/resources/fr/greencodeinitiative/l10n/javascript/rules.json b/javascript-plugin/src/main/resources/fr/greencodeinitiative/l10n/javascript/rules.json deleted file mode 100644 index 598525441..000000000 --- a/javascript-plugin/src/main/resources/fr/greencodeinitiative/l10n/javascript/rules.json +++ /dev/null @@ -1,62 +0,0 @@ -[ - { - "key": "@ecocode/avoid-high-accuracy-geolocation", - "type": "CODE_SMELL", - "name": "Avoid using high accuracy geolocation in web applications", - "description": "\n\n

      Rule details

      \n

      This rule aims at reducing CPU consumption by telling the device to use a less accurate yet more eco friendly geolocation, when geolocation API is used.

      \n

      Examples

      \n

      Examples of non compliant code for this rule:

      \n
      var options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 };\nfunction success(pos) {\n  console.log(pos.coords);\n}\n\nfunction error(err) {\n  console.warn(err);\n}\n\nnavigator.geolocation.getCurrentPosition(success, error, options);\n
      \n

      Examples of compliant code for this rule:

      \n
      // enableHighAccuracy is false by default, so not declaring it is correct\nfunction success(pos) {\n  console.log(pos);\n}\nnavigator.geolocation.getCurrentPosition(success);\n
      \n
      var options = { enableHighAccuracy: false, timeout: 5000, maximumAge: 0 };\nfunction success(pos) {\n  console.log(pos.coords);\n}\n\nfunction error(err) {\n  console.warn(err);\n}\n\nnavigator.geolocation.getCurrentPosition(success, error, options);\n
      \n
      Click here to access the rule details.", - "constantDebtMinutes": 5, - "severity": "MINOR", - "tags": [ - "eco-design", - "ecocode" - ] - }, - { - "key": "@ecocode/no-import-all-from-library", - "type": "CODE_SMELL", - "name": "Should not import all from librar", - "description": "\n\n

      Rule details

      \n

      This rule aims to reduce weight of programs by using only needed modules. Many libraries export only one module by\ndefault, but some of them are exporting ES modules or submodules. We should use them to select more precisly needed\nmodules and avoid unnecessarily overloading files weight.

      \n

      \"Example

      \n

      Example with the well-known lodash library, if you only need "isEmpty" method.

      \n

      Options

      \n

      You can externally add your own libraries to be checked.\nTo add your own libraries you need to modify your .eslintrc.js by adding the following rule configuration:

      \n
      module.exports = {\n  ...yourConf,\n  rules: {\n    "no-import-all-from-library": [\n      "warn",\n      {\n        notAllowedLibraries: ["some-lib"], // will check for -> import someLib from "some-lib"\n        importByNamespaceNotAllowedLibraries: ["some-other-lib"], // will check for -> import * as someOtherLib from "some-other-lib"\n      },\n    ],\n  },\n};\n
      \n

      Examples

      \n

      Examples of non-compliant code for this rule:

      \n
      // Example with lodash\nimport lodash from "lodash";\nimport { isEmpty } from "lodash";\nimport * as lodash from "lodash";\n\n// Example with underscore\nimport _ from "underscore";\n
      \n

      Examples of compliant code for this rule:

      \n
      // Example with lodash (uses submodules)\nimport isEmpty from "lodash/isEmpty";\nimport intersect from "lodash/intersect";\n\n// Example with underscore (uses esm modules)\nimport map from "underscore/modules/map.js";\n
      \n
      Click here to access the rule details.", - "constantDebtMinutes": 5, - "severity": "MINOR", - "tags": [ - "eco-design", - "ecocode" - ] - }, - { - "key": "@ecocode/no-multiple-access-dom-element", - "type": "CODE_SMELL", - "name": "Disallow multiple access of same DOM element", - "description": "\n\n

      Rule details

      \n

      This rule aims to reduce DOM access assigning its object to variable when access multiple time. It saves CPU cycles.

      \n

      Examples

      \n

      Examples of incorrect code for this rule:

      \n
      var el1 = document.getElementById("block1").test1;\nvar el2 = document.getElementById("block1").test2;\n
      \n

      Examples of correct code for this rule:

      \n
      var blockElement = document.getElementById("block1");\nvar el1 = blockElement.test1;\nvar el2 = blockElement.test2;\n
      \n
      Click here to access the rule details.", - "constantDebtMinutes": 5, - "severity": "MINOR", - "tags": [ - "eco-design", - "ecocode" - ] - }, - { - "key": "@ecocode/no-multiple-style-changes", - "type": "CODE_SMELL", - "name": "Disallow multiple style changes at once", - "description": "\n\n

      Rule Details

      \n

      This rule aims to disallow batching multiple style changes at once.

      \n

      To limit the number of repaint/reflow, it is advised to batch style modifications by adding a class containing all style\nchanges that will generate a unique reflow.

      \n

      Examples

      \n

      Examples of non-compliant code for this rule:

      \n
      <script>\n  element.style.height = "800px";\n  element.style.width = "600px";\n  element.style.color = "red";\n</script>\n
      \n

      Examples of compliant code for this rule:

      \n
      <style>\n  .in-error {\n    color: red;\n    height: 800px;\n    width: 800px;\n  }\n</style>\n\n<script>\n  element.addClass("in-error");\n</script>\n
      \n
      Click here to access the rule details.", - "constantDebtMinutes": 5, - "severity": "MINOR", - "tags": [ - "eco-design", - "ecocode" - ] - }, - { - "key": "@ecocode/prefer-collections-with-pagination", - "type": "CODE_SMELL", - "name": "Prefer API collections with pagination", - "description": "\n\n

      Rule details

      \n

      This rule aims to reduce the size and thus the network weight of API returns that may contain many elements. This rule\nis built for the NestJS framework but can work with a controller @Controller() and a decorated method @Get().

      \n

      Examples

      \n

      Examples of non-compliant code for this rule:

      \n
      @Controller()\nclass Test {\n  @Get()\n  public find(): Promise<string[]> {}\n}\n
      \n

      Examples of compliant code for this rule:

      \n
      interface Pagination {\n  items: string[];\n  currentPage: number;\n  totalPages: number;\n}\n\n@Controller()\nclass Test {\n  @Get()\n  public find(): Promise<Pagination> {}\n}\n
      \n
      Click here to access the rule details.", - "constantDebtMinutes": 5, - "severity": "MINOR", - "tags": [ - "eco-design", - "ecocode" - ] - } -] diff --git a/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java b/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java deleted file mode 100644 index 84534777c..000000000 --- a/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptPluginTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package fr.greencodeinitiative.javascript; - -import org.junit.jupiter.api.Test; -import org.sonar.api.Plugin; -import org.sonar.api.SonarRuntime; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -class JavaScriptPluginTest { - - @Test - void extensions() { - SonarRuntime sonarRuntime = mock(SonarRuntime.class); - Plugin.Context context = new Plugin.Context(sonarRuntime); - new JavaScriptPlugin().define(context); - assertThat(context.getExtensions()).hasSize(1); - } - -} diff --git a/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinitionTest.java b/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinitionTest.java deleted file mode 100644 index e90f75d95..000000000 --- a/javascript-plugin/src/test/java/fr/greencodeinitiative/javascript/JavaScriptRulesDefinitionTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package fr.greencodeinitiative.javascript; - -import org.junit.jupiter.api.Test; -import org.sonar.api.server.rule.RulesDefinition; - -import static org.assertj.core.api.Assertions.assertThat; - -class JavaScriptRulesDefinitionTest { - - @Test - void createExternalRepository() { - RulesDefinition.Context context = new RulesDefinition.Context(); - new JavaScriptRulesDefinition().define(context); - assertThat(context.repositories()).hasSize(1); - - RulesDefinition.Repository repository = context.repositories().get(0); - assertThat(repository.isExternal()).isTrue(); - assertThat(repository.language()).isEqualTo("js"); - assertThat(repository.key()).isEqualTo("external_eslint_repo"); - } - -} diff --git a/pom.xml b/pom.xml index 0a13b79b0..cb734538d 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,6 @@ ecocode-rules-specifications python-plugin java-plugin - javascript-plugin php-plugin @@ -58,7 +57,6 @@ 7.19.0.31550 4.3.0.11660 3.29.0.9684 - 10.2.0.21568 2.5.0.1358 @@ -106,15 +104,6 @@ provided - - - org.sonarsource.javascript - sonar-javascript-plugin - ${sonarjavascript.version} - sonar-plugin - provided - - org.sonarsource.php From 469837c34c8245316521a3905541e3fbdaf562b3 Mon Sep 17 00:00:00 2001 From: utarwyn Date: Thu, 13 Jul 2023 22:36:23 +0200 Subject: [PATCH 115/170] Update CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 42fc0e43e..a23dd8551 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Deleted +- [#211](https://github.com/green-code-initiative/ecoCode/pull/211) Move JavaScript plugin to its dedicated repository + ## [1.3.0] - 2023-07-04 ### Added From 5d0011dac0795af2b2a2306bbe01353c5849588e Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 14 Jul 2023 22:43:40 +0700 Subject: [PATCH 116/170] update tool build --- tool_build.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/tool_build.sh b/tool_build.sh index bfac031a1..c6f1fba5f 100755 --- a/tool_build.sh +++ b/tool_build.sh @@ -1,3 +1,4 @@ #!/usr/bin/env sh +rm -rf ./lib/*.jar mvn clean package -DskipTests From 1c935ed329bf7ec880ad466dddecbd9473d39bb4 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 19 Jul 2023 17:19:13 +0700 Subject: [PATCH 117/170] [ISSUE 207] Add SonarCloud analysis for tags --- .github/workflows/build.yml | 2 ++ CHANGELOG.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9a4c5361d..96fd532cd 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,6 +6,8 @@ on: paths-ignore: - '*.md' - '.github/**/*.yml' + tags: + - '[0-9]+.[0-9]+.[0-9]+' pull_request: types: [opened, synchronize, reopened] jobs: diff --git a/CHANGELOG.md b/CHANGELOG.md index a23dd8551..c8c7092a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- [#207](https://github.com/green-code-initiative/ecoCode/issues/207) Add release tag analyzis on SonarCloud + ### Changed ### Deleted From 087726c341784f6d5b7e3ddc15fbd8a0086d372f Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 19 Jul 2023 17:45:27 +0700 Subject: [PATCH 118/170] prepare next release 1.3.1 --- CHANGELOG.md | 12 +++++++++++- docker-compose.yml | 12 ++++++------ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8c7092a7..1dba4d25e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +### Changed + +### Deleted + +## [1.3.1] - 2023-07-19 + +### Added + - [#207](https://github.com/green-code-initiative/ecoCode/issues/207) Add release tag analyzis on SonarCloud ### Changed @@ -145,7 +153,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - First official release of ecocode plugins : java plugin, php plugin and python plugin -[unreleased]: https://github.com/green-code-initiative/ecoCode/compare/v1.3.0...HEAD +[unreleased]: https://github.com/green-code-initiative/ecoCode/compare/v1.3.1...HEAD + +[1.3.1]: https://github.com/green-code-initiative/ecoCode/compare/v1.3.0...v1.3.1 [1.3.0]: https://github.com/green-code-initiative/ecoCode/compare/v1.2.1...v1.3.0 diff --git a/docker-compose.yml b/docker-compose.yml index 6e1351794..7d6d0159d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,14 +16,14 @@ services: SONAR_ES_BOOTSTRAP_CHECKS_DISABLE: 'true' volumes: - type: bind - source: ./java-plugin/target/ecocode-java-plugin-1.3.1-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.3.1-SNAPSHOT.jar + source: ./java-plugin/target/ecocode-java-plugin-1.3.2-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.3.2-SNAPSHOT.jar - type: bind - source: ./php-plugin/target/ecocode-php-plugin-1.3.1-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.3.1-SNAPSHOT.jar + source: ./php-plugin/target/ecocode-php-plugin-1.3.2-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.3.2-SNAPSHOT.jar - type: bind - source: ./python-plugin/target/ecocode-python-plugin-1.3.1-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-python-plugin-1.3.1-SNAPSHOT.jar + source: ./python-plugin/target/ecocode-python-plugin-1.3.2-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-python-plugin-1.3.2-SNAPSHOT.jar - "extensions:/opt/sonarqube/extensions" - "logs:/opt/sonarqube/logs" - "data:/opt/sonarqube/data" From 6a73ef14f423e80aab5503cf5981eb86266d4770 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 19 Jul 2023 17:46:21 +0700 Subject: [PATCH 119/170] [maven-release-plugin] prepare release 1.3.1 --- ecocode-rules-specifications/pom.xml | 32 ++++++++++++++-------------- java-plugin/pom.xml | 2 +- php-plugin/pom.xml | 2 +- pom.xml | 4 ++-- python-plugin/pom.xml | 2 +- 5 files changed, 21 insertions(+), 21 deletions(-) diff --git a/ecocode-rules-specifications/pom.xml b/ecocode-rules-specifications/pom.xml index 6dee12f0d..f024b2b16 100644 --- a/ecocode-rules-specifications/pom.xml +++ b/ecocode-rules-specifications/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.1-SNAPSHOT + 1.3.1 ecocode-rules-specifications @@ -114,38 +114,38 @@ - - + + - + - - + + - + - - + + - + - - + + - + - - + + - +
      diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index 2f4e2476b..122a61857 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.1-SNAPSHOT + 1.3.1 ecocode-java-plugin diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index c034e7e3b..930295740 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.1-SNAPSHOT + 1.3.1 ecocode-php-plugin diff --git a/pom.xml b/pom.xml index cb734538d..cff0e11ce 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ io.ecocode ecocode-parent - 1.3.1-SNAPSHOT + 1.3.1 pom ecoCode Sonar Plugins Project @@ -33,7 +33,7 @@ scm:git:https://github.com/green-code-initiative/ecocode scm:git:https://github.com/green-code-initiative/ecocode https://github.com/green-code-initiative/ecocode - HEAD + 1.3.1 GitHub diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index b2a7d6e60..25b094cb7 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.1-SNAPSHOT + 1.3.1 ecocode-python-plugin From 9a1ce8c4b5bcc68ccf032352770d87acbf7689ab Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 19 Jul 2023 17:46:21 +0700 Subject: [PATCH 120/170] [maven-release-plugin] prepare for next development iteration --- ecocode-rules-specifications/pom.xml | 2 +- java-plugin/pom.xml | 2 +- php-plugin/pom.xml | 2 +- pom.xml | 4 ++-- python-plugin/pom.xml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/ecocode-rules-specifications/pom.xml b/ecocode-rules-specifications/pom.xml index f024b2b16..dd87cf7ca 100644 --- a/ecocode-rules-specifications/pom.xml +++ b/ecocode-rules-specifications/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.1 + 1.3.2-SNAPSHOT ecocode-rules-specifications diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index 122a61857..3e3741972 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.1 + 1.3.2-SNAPSHOT ecocode-java-plugin diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml index 930295740..db8b47669 100644 --- a/php-plugin/pom.xml +++ b/php-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.1 + 1.3.2-SNAPSHOT ecocode-php-plugin diff --git a/pom.xml b/pom.xml index cff0e11ce..a5f7a0c4c 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ io.ecocode ecocode-parent - 1.3.1 + 1.3.2-SNAPSHOT pom ecoCode Sonar Plugins Project @@ -33,7 +33,7 @@ scm:git:https://github.com/green-code-initiative/ecocode scm:git:https://github.com/green-code-initiative/ecocode https://github.com/green-code-initiative/ecocode - 1.3.1 + HEAD GitHub diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml index 25b094cb7..5da4fcb52 100644 --- a/python-plugin/pom.xml +++ b/python-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.1 + 1.3.2-SNAPSHOT ecocode-python-plugin From f3472f652ec2bbe69591eb723b3fb1694756210d Mon Sep 17 00:00:00 2001 From: OLLIVIER Elodie Date: Thu, 6 Apr 2023 10:06:01 +0200 Subject: [PATCH 121/170] EC2-PHP Avoid Multiple IfElse Statements --- .../php/PhpRuleRepository.java | 12 +-- .../AvoidMultipleIfElseStatementCheck.java | 90 +++++++++++++++++++ .../l10n/php/rules/custom/EC2.html | 31 +++++++ ...AvoidMultipleIfElseStatementCheckTest.java | 38 ++++++++ .../checks/AvoidMultipleIfElseStatement.php | 60 +++++++++++++ 5 files changed, 222 insertions(+), 9 deletions(-) create mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java create mode 100644 php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html create mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheckTest.java create mode 100644 php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java index 9c37e58e3..51a82b409 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java @@ -19,14 +19,7 @@ import java.util.List; import fr.greencodeinitiative.php.checks.AvoidGettingSizeCollectionInLoopCheck; -import fr.greencodeinitiative.php.checks.AvoidDoubleQuoteCheck; -import fr.greencodeinitiative.php.checks.AvoidFullSQLRequestCheck; -import fr.greencodeinitiative.php.checks.AvoidSQLRequestInLoopCheck; -import fr.greencodeinitiative.php.checks.AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements; -import fr.greencodeinitiative.php.checks.AvoidUsingGlobalVariablesCheck; -import fr.greencodeinitiative.php.checks.IncrementCheck; -import fr.greencodeinitiative.php.checks.NoFunctionCallWhenDeclaringForLoop; -import fr.greencodeinitiative.php.checks.UseOfMethodsForBasicOperations; +import fr.greencodeinitiative.php.checks.*; import org.sonar.api.SonarRuntime; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.plugins.php.api.visitors.PHPCustomRuleRepository; @@ -69,7 +62,8 @@ public List> checkClasses() { AvoidUsingGlobalVariablesCheck.class, IncrementCheck.class, NoFunctionCallWhenDeclaringForLoop.class, - UseOfMethodsForBasicOperations.class + UseOfMethodsForBasicOperations.class, + AvoidMultipleIfElseStatementCheck.class ); } } diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java new file mode 100644 index 000000000..499e4cfda --- /dev/null +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -0,0 +1,90 @@ +/* + * SonarQube PHP Custom Rules Example + * Copyright (C) 2016-2016 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package fr.greencodeinitiative.php.checks; + +import org.apache.commons.lang.StringUtils; +import org.sonar.check.Priority; +import org.sonar.check.Rule; +import org.sonar.plugins.php.api.tree.Tree; +import org.sonar.plugins.php.api.tree.Tree.Kind; +import org.sonar.plugins.php.api.tree.statement.*; +import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; +import org.sonar.plugins.php.api.visitors.VisitorCheck; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Rule( + key = AvoidMultipleIfElseStatementCheck.RULE_KEY, + name = AvoidMultipleIfElseStatementCheck.ERROR_MESSAGE, + description = AvoidMultipleIfElseStatementCheck.ERROR_MESSAGE, + priority = Priority.MINOR, + tags = {"eco-design", "ecocode"}) +public class AvoidMultipleIfElseStatementCheck extends PHPSubscriptionCheck { + + public static final String RULE_KEY = "EC2"; + public static final String ERROR_MESSAGE = "Use a switch statement instead of multiple if-else if possible"; + + @Override + public List nodesToVisit() { + return Arrays.asList(Kind.IF_STATEMENT); + } + + @Override + public void visitNode(Tree tree) { + checkIfStatement(tree); + checkElseIfStatement(tree); + } + + private void checkIfStatement(Tree tree) { + int countIfStatement = 0; + + Tree parentNode = tree.getParent(); + + if (!(parentNode instanceof BlockTree)) { + return; + } + BlockTree node = (BlockTree) parentNode; + int sizeBody = node.statements().toArray().length; + for(int i=0; i 1){ + context().newIssue(this, tree, ERROR_MESSAGE); + } + } + + private void checkElseIfStatement(Tree tree) { + String ifTree = tree.toString(); + String findStr = "elseif"; + int count = StringUtils.countMatches(ifTree, findStr); + if (count >= 2) { + context().newIssue(this, tree, ERROR_MESSAGE); + } + } + + +} diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html new file mode 100644 index 000000000..d0565879e --- /dev/null +++ b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html @@ -0,0 +1,31 @@ +

      If we are using too many conditional if-else statements it will impact performance since JVM will have to compare the conditions. We can think of using a switch statement instead of multiple if-else if possible. Switch statement has a performance advantage over if – else.

      + +

      Non-compliant Code Example

      +
      +		$index = 1;
      +        $nb = 2;
      +
      +        if ($nb > $index) {
      +            $nb = $nb + $index;
      +        } else {
      +            $nb = $nb - 1;
      +        }
      +        if ($nb != $index + 1) {
      +            $nb = $nb + $index;
      +        } else {
      +            $nb = $nb - 1;
      +        }
      +
      +
      +
      +

      Compliant Code Example

      +
      +        $index = 1;
      +        $nb = 2;
      +
      +        if ($nb > $index) {
      +            $nb = $nb + $index;
      +        } else {
      +            $nb = $nb - 1;
      +        }
      +
      diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheckTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheckTest.java new file mode 100644 index 000000000..50b6bfbef --- /dev/null +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheckTest.java @@ -0,0 +1,38 @@ +/* + * SonarQube PHP Custom Rules Example + * Copyright (C) 2016-2016 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package fr.greencodeinitiative.php.checks; + +import org.junit.Test; +import org.sonar.plugins.php.api.tests.PHPCheckTest; +import org.sonar.plugins.php.api.tests.PhpTestFile; + +import java.io.File; + +/** + * Test class to test the check implementation. + */ +public class AvoidMultipleIfElseStatementCheckTest { + + @Test + public void test() throws Exception { + PHPCheckTest.check(new AvoidMultipleIfElseStatementCheck(), new PhpTestFile(new File("src/test/resources/checks/AvoidMultipleIfElseStatement.php"))); + } + +} diff --git a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php new file mode 100644 index 000000000..906e1e0ef --- /dev/null +++ b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php @@ -0,0 +1,60 @@ + \ No newline at end of file From 790affb48df3da094c0c4b7d34be0b3c3426a8a6 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 6 Jun 2023 23:50:43 +0200 Subject: [PATCH 122/170] [ISSUE 121] update CHANGELOG.md, RULES.md, review feedback --- CHANGELOG.md | 1 + RULES.md | 2 +- .../php/checks/AvoidMultipleIfElseStatementCheck.java | 9 ++------- .../greencodeinitiative/l10n/php/rules/custom/EC2.html | 2 +- 4 files changed, 5 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dba4d25e..c6917d4b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- [#121](https://github.com/green-code-initiative/ecoCode/issues/121) new PHP rule : Multiple if-else statement ### Changed ### Deleted diff --git a/RULES.md b/RULES.md index 49d42e38f..d70919b0c 100644 --- a/RULES.md +++ b/RULES.md @@ -37,7 +37,7 @@ Some are applicable for different technologies. | EC74 | Write SELECT * FROM | The database server must resolve the fields based on the schema. If you are familiar with the diagram, it is strongly recommended to name the fields. | [cnumr best practices (3rd edition) BP_074 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | ✅ | 🚀 | | EC1 | Calling a Spring repository inside a loop | The use of Spring repository in a loop induces unnecessary calculations by the CPU and therefore superfluous energy consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | | EC3 | Getting the size of the collection in the loop | When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. | | ✅ | ✅ | 🚀 | 🚀 | 🚀 | -| EC2 | Multiple if-else statement | Using too many conditional if-else statements will impact performance since JVM will have to compare the conditions. Prefer using a switch statement instead of multiple if-else if possible. Switch statement has a performance advantage over if – else. | | ✅ | 🚧 | 🚀 | 🚧 | 🚀 | +| EC2 | Multiple if-else statement | Using too many conditional if-else statements will impact performance since JVM will have to compare the conditions. Prefer using a switch statement instead of multiple if-else if possible. Switch statement has a performance advantage over if – else. | | ✅ | ✅ | 🚀 | 🚧 | 🚀 | | EC76 | Usage of static collections | Avoid usage of static collections. If you want to use static collections make them final and create for example a singleton if needed containing the collections. The static fields are more complicated for the Garbage Collector to manage and can lead to memory leaks. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | | EC77 | Usage Pattern.compile() in a non-static context | Avoid using Pattern.compile() in a non-static context. This operation requires a non negligible amount of computational power, Using a single match saves CPU cycles and RAM consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | | EC75 | Concatenate Strings in loop | Don't concatenate Strings in loop. User StringBuilder instead. Strings are immutable so each time you concatenate a String, a new String is created. This is a waste of memory and CPU. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java index 499e4cfda..bc58ee975 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -26,21 +26,16 @@ import org.sonar.plugins.php.api.tree.Tree.Kind; import org.sonar.plugins.php.api.tree.statement.*; import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; -import org.sonar.plugins.php.api.visitors.VisitorCheck; -import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; @Rule( key = AvoidMultipleIfElseStatementCheck.RULE_KEY, name = AvoidMultipleIfElseStatementCheck.ERROR_MESSAGE, description = AvoidMultipleIfElseStatementCheck.ERROR_MESSAGE, priority = Priority.MINOR, - tags = {"eco-design", "ecocode"}) + tags = {"eco-design", "ecocode", "performance"}) public class AvoidMultipleIfElseStatementCheck extends PHPSubscriptionCheck { public static final String RULE_KEY = "EC2"; @@ -61,10 +56,10 @@ private void checkIfStatement(Tree tree) { int countIfStatement = 0; Tree parentNode = tree.getParent(); - if (!(parentNode instanceof BlockTree)) { return; } + BlockTree node = (BlockTree) parentNode; int sizeBody = node.statements().toArray().length; for(int i=0; iIf we are using too many conditional if-else statements it will impact performance since JVM will have to compare the conditions. We can think of using a switch statement instead of multiple if-else if possible. Switch statement has a performance advantage over if – else.

      +

      If we are using too many conditional if-else statements it will impact performance since. We can think of using a switch statement instead of multiple if-else if possible. Switch statement has a performance advantage over if – else.

      Non-compliant Code Example

      
      From 96e4aaf46ac33cb1799d06d25c56fa17462a15f7 Mon Sep 17 00:00:00 2001
      From: David DE CARVALHO 
      Date: Wed, 7 Jun 2023 00:17:52 +0200
      Subject: [PATCH 123/170] [ISSUE 121] correction of unit tests + code
       correction StringUtils
      
      ---
       .../AvoidMultipleIfElseStatementCheck.java    | 20 +++++++-
       .../checks/AvoidMultipleIfElseStatement.php   | 48 +++++++++++--------
       2 files changed, 46 insertions(+), 22 deletions(-)
      
      diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java
      index bc58ee975..525739ce2 100644
      --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java
      +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java
      @@ -19,7 +19,6 @@
        */
       package fr.greencodeinitiative.php.checks;
       
      -import org.apache.commons.lang.StringUtils;
       import org.sonar.check.Priority;
       import org.sonar.check.Rule;
       import org.sonar.plugins.php.api.tree.Tree;
      @@ -40,6 +39,7 @@ public class AvoidMultipleIfElseStatementCheck extends PHPSubscriptionCheck {
       
           public static final String RULE_KEY = "EC2";
           public static final String ERROR_MESSAGE = "Use a switch statement instead of multiple if-else if possible";
      +    public static final int INDEX_NOT_FOUND = -1;
       
           @Override
           public List nodesToVisit() {
      @@ -75,11 +75,27 @@ private void checkIfStatement(Tree tree) {
           private void checkElseIfStatement(Tree tree) {
               String ifTree = tree.toString();
               String findStr = "elseif";
      -        int count = StringUtils.countMatches(ifTree, findStr);
      +        int count = countMatches(ifTree, findStr);
               if (count >= 2) {
                  context().newIssue(this, tree, ERROR_MESSAGE);
               }
           }
       
      +    public static int countMatches(String str, String sub) {
      +        if (isEmpty(str) || isEmpty(sub)) {
      +            return 0;
      +        }
      +        int count = 0;
      +        int idx = 0;
      +        while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) {
      +            count++;
      +            idx += sub.length();
      +        }
      +        return count;
      +    }
      +
      +    public static boolean isEmpty(String str) {
      +        return str == null || str.length() == 0;
      +    }
       
       }
      diff --git a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php
      index 906e1e0ef..1e6611192 100644
      --- a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php
      +++ b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php
      @@ -1,24 +1,27 @@
       
      \ No newline at end of file
      
      From 22fe99c5279d5d607f0a49909273196814cff678 Mon Sep 17 00:00:00 2001
      From: David DE CARVALHO 
      Date: Wed, 7 Jun 2023 10:51:12 +0200
      Subject: [PATCH 124/170] [ISSUE 121] adding other use cases on tests -
       implementation to complete
      
      ---
       .../l10n/php/rules/custom/EC2.html            | 42 +++++----
       .../checks/AvoidMultipleIfElseStatement.php   | 88 ++++++++++++++++++-
       2 files changed, 104 insertions(+), 26 deletions(-)
      
      diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html
      index 294bed938..29d6f15f8 100644
      --- a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html
      +++ b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html
      @@ -1,31 +1,29 @@
      -

      If we are using too many conditional if-else statements it will impact performance since. We can think of using a switch statement instead of multiple if-else if possible. Switch statement has a performance advantage over if – else.

      +

      If we are using too many conditional if-else statements it will impact performance. We can think of using a switch statement instead of multiple if-else if possible. Switch statement has a performance advantage over if – else.

      Non-compliant Code Example

      -		$index = 1;
      -        $nb = 2;
      -
      -        if ($nb > $index) {
      -            $nb = $nb + $index;
      -        } else {
      -            $nb = $nb - 1;
      -        }
      -        if ($nb != $index + 1) {
      -            $nb = $nb + $index;
      -        } else {
      -            $nb = $nb - 1;
      -        }
      -
      +    $index = 1;
      +    $nb = 2;
       
      +    if ($nb > $index) {
      +        $nb = $nb + $index;
      +    } else {
      +        $nb = $nb - 1;
      +    }
      +    if ($nb != $index + 1) {
      +        $nb = $nb + $index;
      +    } else {
      +        $nb = $nb - 1;
      +    }
       

      Compliant Code Example

      -        $index = 1;
      -        $nb = 2;
      +    $index = 1;
      +    $nb = 2;
       
      -        if ($nb > $index) {
      -            $nb = $nb + $index;
      -        } else {
      -            $nb = $nb - 1;
      -        }
      +    if ($nb > $index) {
      +        $nb = $nb + $index;
      +    } else {
      +        $nb = $nb - 1;
      +    }
       
      diff --git a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php index 1e6611192..d71ba5556 100644 --- a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php +++ b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php @@ -26,12 +26,12 @@ public function methodWithMultipleIfElse() if ($nb1 == 1) { // NOK {{Use a switch statement instead of multiple if-else if possible}} $nb1 = 1; } else { - // + $nb1 = 2; } - if ($nb1 == 1) { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 1; + if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb1 = 3; } else { - $nb1 = 2; + $nb1 = 4; } return $nb1; @@ -65,4 +65,84 @@ public function methodWithOneIfElse() return $nb1; } + + public function methodWithMultipleIfElseDifferentVariables() // Compliant (2 if on different variables) + { + $nb1 = 0; + $nb2 = 0; + + if ($nb1 == 1) { + $nb1 = 1; + } else { + $nb2 = 2; + } + + if ($nb2 == 2) { + $nb1 = 3; + } else { + $nb1 = 4; + } + + return $nb1; + } + + public function methodWithMultipleIfElseIfSeparated() // Compliant (only 2 if on the same variable) + { + $nb1 = 0; + + if ($nb1 == 1) { + $nb1 = 1; + } else { + if ($nb1 == 2) { + $nb1 = 3; + } else { + $nb1 = 2; + } + } + + return $nb1; + } + + public function methodWithMultipleIfElseIfSeparatedDeep() + { + $nb1 = 0; + + if ($nb1 == 1) { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb1 = 1; + } else { + if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb1 = 3; + } else { + if ($nb1 == 3) { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb1 = 4; + } else { + $nb1 = 5; + } + } + } + + return $nb1; + } + + public function methodWithMultipleIfElseIfSeparatedDeepButDifferentVariables() // Compliant + { + $nb1 = 0; + $nb2 = 0; + + if ($nb1 == 1) { + $nb1 = 1; + } else { + if ($nb1 == 2) { + $nb1 = 3; + } else { + if ($nb2 == 2) { + $nb1 = 3; + } else { + $nb1 = 2; + } + } + } + + return $nb1; + } } From f06cb88a65e814aa34fef72648228efe80d4e0f2 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 11 Jul 2023 10:20:30 +0700 Subject: [PATCH 125/170] refactoring use case multiple-if-else --- RULES.md | 86 ++-- TODOs_DDC.md | 19 + .../checks/AvoidMultipleIfElseStatement.java | 3 + .../AvoidMultipleIfElseStatementCheck.java | 67 ++- ...dMultipleIfElseStatementCheck__BACKUP.java | 103 +++++ .../l10n/php/rules/custom/EC2.html | 67 ++- .../checks/AvoidMultipleIfElseStatement.php | 382 ++++++++++++------ 7 files changed, 539 insertions(+), 188 deletions(-) create mode 100644 TODOs_DDC.md create mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck__BACKUP.java diff --git a/RULES.md b/RULES.md index d70919b0c..3d03ed6d9 100644 --- a/RULES.md +++ b/RULES.md @@ -9,46 +9,46 @@ Some are applicable for different technologies. - 🚀 Rule to implement - 🚫 Non applicable rule -| Rule key | Name | Description | Reference/Validation | Java | Php | JS | Python | Rust | -|-|--|--|--|--|--|--|--|--| -| | Use official social media sharing buttons | These JavaScript plugins are very resource-intensive: to work, they require a large number of requests and download heavy files. It is better to prefer direct links. | [cnumr best practices (3rd edition) BP_019](https://github.com/cnumr/best-practices/blob/main/chapters/BP_019_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | -| | Non-grouped similar CSS declarations | When multiple Document Object Model (DOM) elements have common CSS properties, declare them together in the same style sheet. This method reduces the weight of CSS. |[cnumr best practices (3rd edition) BP_025](https://github.com/cnumr/best-practices/blob/main/chapters/BP_025_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | -| | CSS shorthand notations not used | Reduces the weight of the style sheet. | [cnumr best practices (3rd edition) BP_026](https://github.com/cnumr/best-practices/blob/main/chapters/BP_026_fr.md) | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | -| | CSS print not included | This style sheet reduces the number of pages printed. | [cnumr best practices (3rd edition) BP_027](https://github.com/cnumr/best-practices/blob/main/chapters/BP_027_fr.md) | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | -| | Non-standard fonts used | Prefer standard fonts, as they are already present on the user's computer, so they do not need to download them. This saves bandwidth, while speeding up the display of the site. | [cnumr best practices (3rd edition) BP_029](https://github.com/cnumr/best-practices/blob/main/chapters/BP_029_fr.md) | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | -| | Non-outsourced CSS and Javascript | If you include CSS or JavaScript code in the body of the HTML file, while the HTML file is used by several pages (or even the entire site), this code must be transferred for each page requested by the user, which increases the volume of data transmitted. | [cnumr best practices (3rd edition) BP_032](https://github.com/cnumr/best-practices/blob/main/chapters/BP_032_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | -| | Resize images browser-side | Do not resize images using the HEIGHT and WIDTH attributes of the HTML code. This approach requires transferring these images to their original size, wasting bandwidth and CPU cycles. | [cnumr best practices (3rd edition) BP_034](https://github.com/cnumr/best-practices/blob/main/chapters/BP_034_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | -| EC10 | Use unoptimized vector images | Less heavy SVG images using less bandwidth | [cnumr best practices (3rd edition) BP_036](https://github.com/cnumr/best-practices/blob/main/chapters/BP_036_fr.md) | 🚧 | 🚀 | 🚀 | ✅ | 🚀 | -| | Using too many CSS/javascript animations | JavaScript/CSS animations can be very expensive in terms of CPU cycles and memory consumption. | [cnumr best practices (3rd edition) BP_039](https://github.com/cnumr/best-practices/blob/main/chapters/BP_039_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | -| | Modify the DOM when traversing it | Modifying the DOM (Document Object Model) as you traverse it can lead to situations where the loop becomes very resource-intensive, especially CPU cycles. | [cnumr best practices (3rd edition) BP_041](https://github.com/cnumr/best-practices/blob/main/chapters/BP_041_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | -| | Edit DOM elements to make it invisible | When an element of the Document Object Model (DOM) needs to be modified by several properties, each change in style or content will generate a repaint or reflow. | [cnumr best practices (3rd edition) BP_042](https://github.com/cnumr/best-practices/blob/main/chapters/BP_042_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | -| | Modify several CSS properties all at once | To limit the number of repaints/reflows, it is recommended not to modify properties one by one. (linter key : `@ecocode/no-multiple-style-changes`) | [cnumr best practices (3rd edition) BP_045](https://github.com/cnumr/best-practices/blob/main/chapters/BP_045_fr.md) | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | -| EC34 | Using try...catch...finally calls | When an exception is thrown, a variable (the exception itself) is created in the catch block and destroyed at the end of the block. Creating this variable and destroying it consumes CPU cycles and RAM unnecessarily. That is why it is important not to use this construction and to prefer, as much as possible, a logical test. | [cnumr best practices (3rd edition) BP_047 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | ✅ | 🚀 | ✅ | 🚀 | -| EC22 | The use of methods for basic operations | Using methods for basic operations consumes additional system resources. The interpreter must in effect and solve the objects and then the methods, just to carry out these simple operations of the language. | [cnumr best practices (3rd edition) BP_048 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | ✅ | 🚀 | 🚀 | 🚀 | -| ??? | Call a DOM element multiple times without caching (linter key : `@ecocode/no-multiple-access-dom-element`) | Access to the Document Object Model (DOM) is costly in terms of CPU resources (CPU cycles). Also, when you use the same DOM element from JavaScript multiple times, store its reference in a variable so that you do not go through the DOM again for the same element. | [cnumr best practices (3rd edition) BP_049](https://github.com/cnumr/best-practices/blob/main/chapters/BP_049_fr.md) | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | -| EC4 | Use global variables | When using a global variable, the interpretation engine must check: 1) that it exists in the current scope, in the one above, etc. ; 2) the variable has a value; 3) ... To avoid all these checks, it is often possible to pass the useful variables as arguments of routines, making them local. This process saves computational time (CPU cycles). | [cnumr best practices (3rd edition) BP_050 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | ✅ | 🚀 | -| EC53 | Using arrays in foreach loops | foreach deduplicates items in a list before starting the enumeration. It is therefore generally more economical to use a simple for loop when you have a good command of the collection. | [cnumr best practices (3rd edition) BP_053 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | 🚀 | 🚀 | 🚀 | 🚀 | -| EC7 | Rewrite native getter/setters | Overloading them lengthens the compilation and execution times of these methods, which are usually much better optimized by the language than by the developer. | [cnumr best practices (3rd edition) BP_062 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | 🚀 | 🚀 | ✅ | 🚀 | -| EC63 | Unnecessarily assigning values to variables | Avoid declaring and using variables when it is not indis-thinkable. Indeed, each allocation corresponds to the RAM occupied. | [cnumr best practices (3rd edition) BP_063 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | 🚀 | 🚀 | 🚀 | 🚀 | -| EC66 | Use single quote (') instead of quotation mark (") | The shape using the quotation marks allows the developer to insert variables that will be substituted at run time. But if the string does not have a variable, use quotes instead. Thus, language will not look for variables to subtituture, which will reduce the consumption of CPU cycles. | [cnumr best practices (3rd edition) BP_066 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | ✅ | 🚀 | ✅ | 🚀 | -| EC67 | Use the $i++ variable during an iteration | The $i++ form has the disadvantage of generating a tem-porary variable during incrementation, which is not the case with the ++$i form. | [cnumr best practices (3rd edition) BP_067 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | 🚀 | 🚀 | -| EC69 | Calling a function in the declaration of a for loop | Avoid calling the function each time the loop is iterated. | [cnumr best practices (3rd edition) BP_069 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | ✅ | 🚀 | -| EC72 | Perform an SQL query inside a loop | Servers are optimized to process multiple selections, insertions, or changes in a single query or transaction. consume CPU cycles, RAM, and bandwidth unnecessarily. | [cnumr best practices (3rd edition) BP_072](https://github.com/cnumr/best-practices/blob/main/chapters/BP_072_fr.md) | ✅ | ✅ | 🚀 | ✅ | 🚀 | -| EC74 | Write SELECT * FROM | The database server must resolve the fields based on the schema. If you are familiar with the diagram, it is strongly recommended to name the fields. | [cnumr best practices (3rd edition) BP_074 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | ✅ | 🚀 | -| EC1 | Calling a Spring repository inside a loop | The use of Spring repository in a loop induces unnecessary calculations by the CPU and therefore superfluous energy consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | -| EC3 | Getting the size of the collection in the loop | When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. | | ✅ | ✅ | 🚀 | 🚀 | 🚀 | -| EC2 | Multiple if-else statement | Using too many conditional if-else statements will impact performance since JVM will have to compare the conditions. Prefer using a switch statement instead of multiple if-else if possible. Switch statement has a performance advantage over if – else. | | ✅ | ✅ | 🚀 | 🚧 | 🚀 | -| EC76 | Usage of static collections | Avoid usage of static collections. If you want to use static collections make them final and create for example a singleton if needed containing the collections. The static fields are more complicated for the Garbage Collector to manage and can lead to memory leaks. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | -| EC77 | Usage Pattern.compile() in a non-static context | Avoid using Pattern.compile() in a non-static context. This operation requires a non negligible amount of computational power, Using a single match saves CPU cycles and RAM consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | -| EC75 | Concatenate Strings in loop | Don't concatenate Strings in loop. User StringBuilder instead. Strings are immutable so each time you concatenate a String, a new String is created. This is a waste of memory and CPU. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | -| EC78 | Const parameter in batch update | Don't set const parameter in batch update => Put its in query. Creating this parameter and destroying it consumes CPU cycles and RAM unnecessarily. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | -| EC79 | Free resources | try-with-resources Statement needs to be implemented for any object that implements the AutoCloseable interface, it save computer resources. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | -| EC32 | Initialize builder/buffer with the appropriate size | If you know in advance how many characters would be appended, initialize builder/buffer with the appropriate size. They will thus never have to be resized. This saves CPU cycles and therefore consumes less energy. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | -| EC28 | Optimize read file exceptions | | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | -| EC5 | Usage of preparedStatement instead of Statement | SQL will only commit the query once, whereas if you used only one statement, it would commit the query every time and thus induce unnecessary calculations by the CPU and therefore superfluous energy consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | -| EC27 | Usage of system.arraycopy to copy arrays | Programs spend most of the time in loops. These can be resource consuming, especially when they integrate heavy processing (IO access). Moreover, the size of the data and processing inside the loops will not allow full use of hardware mechanisms such as the cache or compiler optimization mechanisms. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | -| EC404 | Avoid list comprehension in iterations | Use generator comprehension instead of list comprehension in for loop declaration | | 🚫 | 🚫 | 🚫 | ✅ | 🚫 | -| EC203 | Detect unoptimized file formats | When it is possible, to use svg format image over other image format | | 🚀 | 🚀 | 🚀 | ✅ | 🚀 | -| | Avoid high accuracy geolocation | Avoid using high accuracy geolocation in web applications (linter key : `@ecocode/avoid-high-accuracy-geolocation`) | | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | -| | No import all from library | Should not import all from library (linter key : `@ecocode/no-import-all-from-library`) | | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | -| | Prefer collections with pagination | Prefer API collections with pagination (linter key : `@ecocode/prefer-collections-with-pagination`) | | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | +| Rule key | Name | Description | Reference/Validation | Java | Php | JS | Python | Rust | +|----------|------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------|-----|----|--------|------| +| | Use official social media sharing buttons | These JavaScript plugins are very resource-intensive: to work, they require a large number of requests and download heavy files. It is better to prefer direct links. | [cnumr best practices (3rd edition) BP_019](https://github.com/cnumr/best-practices/blob/main/chapters/BP_019_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | +| | Non-grouped similar CSS declarations | When multiple Document Object Model (DOM) elements have common CSS properties, declare them together in the same style sheet. This method reduces the weight of CSS. | [cnumr best practices (3rd edition) BP_025](https://github.com/cnumr/best-practices/blob/main/chapters/BP_025_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | +| | CSS shorthand notations not used | Reduces the weight of the style sheet. | [cnumr best practices (3rd edition) BP_026](https://github.com/cnumr/best-practices/blob/main/chapters/BP_026_fr.md) | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | +| | CSS print not included | This style sheet reduces the number of pages printed. | [cnumr best practices (3rd edition) BP_027](https://github.com/cnumr/best-practices/blob/main/chapters/BP_027_fr.md) | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | +| | Non-standard fonts used | Prefer standard fonts, as they are already present on the user's computer, so they do not need to download them. This saves bandwidth, while speeding up the display of the site. | [cnumr best practices (3rd edition) BP_029](https://github.com/cnumr/best-practices/blob/main/chapters/BP_029_fr.md) | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | +| | Non-outsourced CSS and Javascript | If you include CSS or JavaScript code in the body of the HTML file, while the HTML file is used by several pages (or even the entire site), this code must be transferred for each page requested by the user, which increases the volume of data transmitted. | [cnumr best practices (3rd edition) BP_032](https://github.com/cnumr/best-practices/blob/main/chapters/BP_032_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | +| | Resize images browser-side | Do not resize images using the HEIGHT and WIDTH attributes of the HTML code. This approach requires transferring these images to their original size, wasting bandwidth and CPU cycles. | [cnumr best practices (3rd edition) BP_034](https://github.com/cnumr/best-practices/blob/main/chapters/BP_034_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | +| EC10 | Use unoptimized vector images | Less heavy SVG images using less bandwidth | [cnumr best practices (3rd edition) BP_036](https://github.com/cnumr/best-practices/blob/main/chapters/BP_036_fr.md) | 🚧 | 🚀 | 🚀 | ✅ | 🚀 | +| | Using too many CSS/javascript animations | JavaScript/CSS animations can be very expensive in terms of CPU cycles and memory consumption. | [cnumr best practices (3rd edition) BP_039](https://github.com/cnumr/best-practices/blob/main/chapters/BP_039_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | +| | Modify the DOM when traversing it | Modifying the DOM (Document Object Model) as you traverse it can lead to situations where the loop becomes very resource-intensive, especially CPU cycles. | [cnumr best practices (3rd edition) BP_041](https://github.com/cnumr/best-practices/blob/main/chapters/BP_041_fr.md) | 🚫 | 🚫 | 🚧 | 🚫 | 🚫 | +| | Edit DOM elements to make it invisible | When an element of the Document Object Model (DOM) needs to be modified by several properties, each change in style or content will generate a repaint or reflow. | [cnumr best practices (3rd edition) BP_042](https://github.com/cnumr/best-practices/blob/main/chapters/BP_042_fr.md) | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | +| | Modify several CSS properties all at once | To limit the number of repaints/reflows, it is recommended not to modify properties one by one. (linter key : `@ecocode/no-multiple-style-changes`) | [cnumr best practices (3rd edition) BP_045](https://github.com/cnumr/best-practices/blob/main/chapters/BP_045_fr.md) | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | +| EC34 | Using try...catch...finally calls | When an exception is thrown, a variable (the exception itself) is created in the catch block and destroyed at the end of the block. Creating this variable and destroying it consumes CPU cycles and RAM unnecessarily. That is why it is important not to use this construction and to prefer, as much as possible, a logical test. | [cnumr best practices (3rd edition) BP_047 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | ✅ | 🚀 | ✅ | 🚀 | +| EC22 | The use of methods for basic operations | Using methods for basic operations consumes additional system resources. The interpreter must in effect and solve the objects and then the methods, just to carry out these simple operations of the language. | [cnumr best practices (3rd edition) BP_048 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | ✅ | 🚀 | 🚀 | 🚀 | +| ??? | Call a DOM element multiple times without caching (linter key : `@ecocode/no-multiple-access-dom-element`) | Access to the Document Object Model (DOM) is costly in terms of CPU resources (CPU cycles). Also, when you use the same DOM element from JavaScript multiple times, store its reference in a variable so that you do not go through the DOM again for the same element. | [cnumr best practices (3rd edition) BP_049](https://github.com/cnumr/best-practices/blob/main/chapters/BP_049_fr.md) | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | +| EC4 | Use global variables | When using a global variable, the interpretation engine must check: 1) that it exists in the current scope, in the one above, etc. ; 2) the variable has a value; 3) ... To avoid all these checks, it is often possible to pass the useful variables as arguments of routines, making them local. This process saves computational time (CPU cycles). | [cnumr best practices (3rd edition) BP_050 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | ✅ | 🚀 | +| EC53 | Using arrays in foreach loops | foreach deduplicates items in a list before starting the enumeration. It is therefore generally more economical to use a simple for loop when you have a good command of the collection. | [cnumr best practices (3rd edition) BP_053 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | 🚀 | 🚀 | 🚀 | 🚀 | +| EC7 | Rewrite native getter/setters | Overloading them lengthens the compilation and execution times of these methods, which are usually much better optimized by the language than by the developer. | [cnumr best practices (3rd edition) BP_062 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | 🚀 | 🚀 | ✅ | 🚀 | +| EC63 | Unnecessarily assigning values to variables | Avoid declaring and using variables when it is not indis-thinkable. Indeed, each allocation corresponds to the RAM occupied. | [cnumr best practices (3rd edition) BP_063 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | 🚀 | 🚀 | 🚀 | 🚀 | +| EC66 | Use single quote (') instead of quotation mark (") | The shape using the quotation marks allows the developer to insert variables that will be substituted at run time. But if the string does not have a variable, use quotes instead. Thus, language will not look for variables to subtituture, which will reduce the consumption of CPU cycles. | [cnumr best practices (3rd edition) BP_066 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | ✅ | 🚀 | ✅ | 🚀 | +| EC67 | Use the $i++ variable during an iteration | The $i++ form has the disadvantage of generating a tem-porary variable during incrementation, which is not the case with the ++$i form. | [cnumr best practices (3rd edition) BP_067 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | 🚀 | 🚀 | +| EC69 | Calling a function in the declaration of a for loop | Avoid calling the function each time the loop is iterated. | [cnumr best practices (3rd edition) BP_069 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | ✅ | 🚀 | +| EC72 | Perform an SQL query inside a loop | Servers are optimized to process multiple selections, insertions, or changes in a single query or transaction. consume CPU cycles, RAM, and bandwidth unnecessarily. | [cnumr best practices (3rd edition) BP_072](https://github.com/cnumr/best-practices/blob/main/chapters/BP_072_fr.md) | ✅ | ✅ | 🚀 | ✅ | 🚀 | +| EC74 | Write SELECT * FROM | The database server must resolve the fields based on the schema. If you are familiar with the diagram, it is strongly recommended to name the fields. | [cnumr best practices (3rd edition) BP_074 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | ✅ | 🚀 | +| EC1 | Calling a Spring repository inside a loop | The use of Spring repository in a loop induces unnecessary calculations by the CPU and therefore superfluous energy consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | +| EC3 | Getting the size of the collection in the loop | When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. | | ✅ | ✅ | 🚀 | 🚀 | 🚀 | +| EC2 | Multiple if-else statement | Using too many conditional if-else statements will impact performance since JVM will have to compare the conditions. Prefer using a switch statement instead of multiple if-else if possible, or refactor your code to reduce conditonnal statements on the same variable. Switch statement has a performance advantage over if – else. | | ✅ | ✅ | 🚀 | 🚧 | 🚀 | +| EC76 | Usage of static collections | Avoid usage of static collections. If you want to use static collections make them final and create for example a singleton if needed containing the collections. The static fields are more complicated for the Garbage Collector to manage and can lead to memory leaks. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | +| EC77 | Usage Pattern.compile() in a non-static context | Avoid using Pattern.compile() in a non-static context. This operation requires a non negligible amount of computational power, Using a single match saves CPU cycles and RAM consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | +| EC75 | Concatenate Strings in loop | Don't concatenate Strings in loop. User StringBuilder instead. Strings are immutable so each time you concatenate a String, a new String is created. This is a waste of memory and CPU. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | +| EC78 | Const parameter in batch update | Don't set const parameter in batch update => Put its in query. Creating this parameter and destroying it consumes CPU cycles and RAM unnecessarily. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | +| EC79 | Free resources | try-with-resources Statement needs to be implemented for any object that implements the AutoCloseable interface, it save computer resources. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | +| EC32 | Initialize builder/buffer with the appropriate size | If you know in advance how many characters would be appended, initialize builder/buffer with the appropriate size. They will thus never have to be resized. This saves CPU cycles and therefore consumes less energy. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | +| EC28 | Optimize read file exceptions | | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | +| EC5 | Usage of preparedStatement instead of Statement | SQL will only commit the query once, whereas if you used only one statement, it would commit the query every time and thus induce unnecessary calculations by the CPU and therefore superfluous energy consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | +| EC27 | Usage of system.arraycopy to copy arrays | Programs spend most of the time in loops. These can be resource consuming, especially when they integrate heavy processing (IO access). Moreover, the size of the data and processing inside the loops will not allow full use of hardware mechanisms such as the cache or compiler optimization mechanisms. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | +| EC404 | Avoid list comprehension in iterations | Use generator comprehension instead of list comprehension in for loop declaration | | 🚫 | 🚫 | 🚫 | ✅ | 🚫 | +| EC203 | Detect unoptimized file formats | When it is possible, to use svg format image over other image format | | 🚀 | 🚀 | 🚀 | ✅ | 🚀 | +| | Avoid high accuracy geolocation | Avoid using high accuracy geolocation in web applications (linter key : `@ecocode/avoid-high-accuracy-geolocation`) | | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | +| | No import all from library | Should not import all from library (linter key : `@ecocode/no-import-all-from-library`) | | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | +| | Prefer collections with pagination | Prefer API collections with pagination (linter key : `@ecocode/prefer-collections-with-pagination`) | | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | diff --git a/TODOs_DDC.md b/TODOs_DDC.md new file mode 100644 index 000000000..20f74d2d9 --- /dev/null +++ b/TODOs_DDC.md @@ -0,0 +1,19 @@ +TODOS dev DDC +=== + +actions vues en séance weekly-meeting : + +- ecoCode-android : nettoyer packages (suite au release) +- teams : nettoyer anciennes équipes + +actions vues perso : + +- nettoyer le MIGRATION_TODOs.md +- ménage dans les branches de dev (local et remote) +- JYC : suppression dépendance analyser-commons ==> check si bien tout nettoyé (version dans pom, référence dans code) +- créer issue sur la rule EC2 sur JAVA : + - à refondre avec les uses cases du PHP + implem du PHP (en cours - PR_160_recup) + - JAVA : existe depuis longtemps !!! normal que l'implem PHP et python aient le même code minimaliste fonctionellement +- voir les rules désativées chez PJ, créer des issues et corriger : + - voir si justement s'il n'y a pas la EC2 dans le lot + - voir pourquoi désactivées car ralaient trop \ No newline at end of file diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java index 9460642ab..d66fd4583 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java @@ -12,6 +12,9 @@ import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; @Rule(key = "EC2") + * functional RULES : please see HTML description file of this rule (resources directory) + */ + @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "AMIES") public class AvoidMultipleIfElseStatement extends IssuableSubscriptionVisitor { protected static final String RULE_MESSAGE = "Using a switch statement instead of multiple if-else if possible"; diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java index 525739ce2..1891e7114 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -26,9 +26,14 @@ import org.sonar.plugins.php.api.tree.statement.*; import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; -import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; +/** + * functional description : please see HTML description file of this rule (resources directory) + */ @Rule( key = AvoidMultipleIfElseStatementCheck.RULE_KEY, name = AvoidMultipleIfElseStatementCheck.ERROR_MESSAGE, @@ -43,16 +48,27 @@ public class AvoidMultipleIfElseStatementCheck extends PHPSubscriptionCheck { @Override public List nodesToVisit() { - return Arrays.asList(Kind.IF_STATEMENT); + return List.of(Kind.IF_STATEMENT, Kind.ELSEIF_CLAUSE, Kind.ELSE_CLAUSE); } @Override public void visitNode(Tree tree) { - checkIfStatement(tree); - checkElseIfStatement(tree); + Tree parentNode = tree.getParent(); + if ( ! (parentNode instanceof BlockTree)) { + return; + } + + visitConditionalNodes(0, new VariablesPerLevelDataStructure()); + +// checkIfStatementAtTheSameLevel(tree); +// checkElseIfStatement(tree); } - private void checkIfStatement(Tree tree) { + private void visitConditionalNodes(int level, VariablesPerLevelDataStructure parentDataMap) { + + } + + private void checkIfStatementAtTheSameLevel(Tree tree) { int countIfStatement = 0; Tree parentNode = tree.getParent(); @@ -60,8 +76,9 @@ private void checkIfStatement(Tree tree) { return; } + // getting parent bloc to count if several IF at the same level BlockTree node = (BlockTree) parentNode; - int sizeBody = node.statements().toArray().length; + int sizeBody = node.statements().size(); for(int i=0; i> ==> + - Key : index of Level (1 = first level) + - Value : Map + - Key : name of variable in the current level + - Value : number of usage of this variable in a IF statement in current level or one of parent levels + */ + private final Map> mapVariablesPerLevel; + + public VariablesPerLevelDataStructure() { + mapVariablesPerLevel = new HashMap<>(10); + } + + public VariablesPerLevelDataStructure(Map> pMapVariablesPerLevel) { + mapVariablesPerLevel = Map.copyOf(pMapVariablesPerLevel); + } + + public void incrementUsageForVariableForLevel(String variableName, int level) { + + // variables map initilization if absent + Map mapVariables = mapVariablesPerLevel.computeIfAbsent(level, k -> new HashMap<>(5)); + + Integer nbUsed = mapVariables.get(variableName); + if (nbUsed == null) { + nbUsed = 0; + } + nbUsed++; + mapVariables.put(variableName, nbUsed); + } } } diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck__BACKUP.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck__BACKUP.java new file mode 100644 index 000000000..631781924 --- /dev/null +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck__BACKUP.java @@ -0,0 +1,103 @@ +/* + * SonarQube PHP Custom Rules Example + * Copyright (C) 2016-2016 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package fr.greencodeinitiative.php.checks; + +import org.sonar.check.Priority; +import org.sonar.check.Rule; +import org.sonar.plugins.php.api.tree.Tree; +import org.sonar.plugins.php.api.tree.Tree.Kind; +import org.sonar.plugins.php.api.tree.statement.BlockTree; +import org.sonar.plugins.php.api.tree.statement.IfStatementTree; +import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; + +import java.util.List; + +@Rule( + key = AvoidMultipleIfElseStatementCheck__BACKUP.RULE_KEY, + name = AvoidMultipleIfElseStatementCheck__BACKUP.ERROR_MESSAGE, + description = AvoidMultipleIfElseStatementCheck__BACKUP.ERROR_MESSAGE, + priority = Priority.MINOR, + tags = {"eco-design", "ecocode", "performance"}) +public class AvoidMultipleIfElseStatementCheck__BACKUP extends PHPSubscriptionCheck { + + public static final String RULE_KEY = "EC2"; + public static final String ERROR_MESSAGE = "Use a switch statement instead of multiple if-else if possible"; + public static final int INDEX_NOT_FOUND = -1; + + @Override + public List nodesToVisit() { + return List.of(Kind.IF_STATEMENT); +// return List.of(Kind.IF_STATEMENT, Kind.ELSEIF_CLAUSE); + } + + @Override + public void visitNode(Tree tree) { + checkIfStatementAtTheSameLevel(tree); + checkElseIfStatement(tree); + } + + private void checkIfStatementAtTheSameLevel(Tree tree) { + int countIfStatement = 0; + + Tree parentNode = tree.getParent(); + if (!(parentNode instanceof BlockTree)) { + return; + } + + // getting parent bloc to count if several IF at the same level + BlockTree node = (BlockTree) parentNode; + int sizeBody = node.statements().size(); + for(int i=0; i 1){ + context().newIssue(this, tree, ERROR_MESSAGE); + } + } + + private void checkElseIfStatement(Tree tree) { + String ifTree = tree.toString(); + String findStr = "elseif"; + int count = countMatches(ifTree, findStr); + if (count >= 2) { + context().newIssue(this, tree, ERROR_MESSAGE); + } + } + + public static int countMatches(String str, String sub) { + if (isBlankString(str) || isBlankString(sub)) { + return 0; + } + int count = 0; + int idx = 0; + while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) { + count++; + idx += sub.length(); + } + return count; + } + + public static boolean isBlankString(String str) { + return str == null || str.length() == 0 || str.isBlank(); + } + +} diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html index 29d6f15f8..a31225e3e 100644 --- a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html +++ b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html @@ -1,29 +1,66 @@ -

      If we are using too many conditional if-else statements it will impact performance. We can think of using a switch statement instead of multiple if-else if possible. Switch statement has a performance advantage over if – else.

      +

      + If we are using too many conditional IF, ELSEIF or ELSE statements it will impact performance. + We can think of using a switch statement instead of multiple if-else if possible, or refactor code + to reduce number of IF, ELSEIF and ELSE statements. + Switch statement has a performance advantage over if – else. +

      +

      + Functional rules : + - one variable must be used maximum twice in IF / ELSEIF / ELSE statements at the same level - WARNINGs : + - IF and ELSEIF statements use explicitly variable names ! + - ELSE statements sue implicity variabel names ! + - one variable must be used maximum twice in IF / ELSEIF / ELSE statements at differents hierarchical levels + - we can assume that if one variable is used three times or more (like explain previously), we should : + - use a SWITCH statement instead + - or refactor the code if possible +

      Non-compliant Code Example

      +

      + NON compliant, becasue `$nb` is used 4 times : + - 2 explicit times in IF statements + - 2 implicit times in ELSE statements +

           $index = 1;
           $nb = 2;
      -
      -    if ($nb > $index) {
      -        $nb = $nb + $index;
      -    } else {
      -        $nb = $nb - 1;
      -    }
      -    if ($nb != $index + 1) {
      -        $nb = $nb + $index;
      +    ...
      +    if ($nb == 0) {
      +        $nb = $index;
      +    } elseif ($nb == 1) {
      +        $nb = $index * 2;
      +    } elseif ($nb == 2) {
      +        $nb = $index * 3;
           } else {
      -        $nb = $nb - 1;
      +        $nb = -1;
           }
       
      -

      Compliant Code Example

      +

      Compliant Code Example : refactor solution

           $index = 1;
           $nb = 2;
      -
      -    if ($nb > $index) {
      -        $nb = $nb + $index;
      +    ...
      +    if ($nb == 0 || $nb == 1 || $nb == 2) {
      +        $nb = $index * ($nb + 1);
           } else {
      -        $nb = $nb - 1;
      +        $nb = -1;
           }
      +    return $nb;
       
      + +

      Compliant Code Example : SWITCH statement solution

      +
      +    $index = 1;
      +    $nb = 2;
      +    ...
      +    switch ($nb) {
      +        case 0:
      +        case 1:
      +        case 2:
      +            $nb = $index * ($nb + 1);
      +            break;
      +        default:
      +            $nb = -1;
      +    }
      +    return $nb;
      +
      \ No newline at end of file diff --git a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php index d71ba5556..e868eb1b6 100644 --- a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php +++ b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php @@ -1,72 +1,21 @@ Date: Wed, 19 Jul 2023 16:59:25 +0700 Subject: [PATCH 126/170] [ISSUE 121] refactoring use case multiple-if-else - BIS --- .../AvoidMultipleIfElseStatementCheck.java | 255 +++++++++++++----- .../checks/AvoidMultipleIfElseStatement.php | 115 ++++---- 2 files changed, 253 insertions(+), 117 deletions(-) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java index 1891e7114..103b0983e 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -19,14 +19,19 @@ */ package fr.greencodeinitiative.php.checks; +import org.sonar.api.utils.log.Logger; +import org.sonar.api.utils.log.Loggers; import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.php.api.tree.Tree; import org.sonar.plugins.php.api.tree.Tree.Kind; +import org.sonar.plugins.php.api.tree.declaration.MethodDeclarationTree; +import org.sonar.plugins.php.api.tree.expression.BinaryExpressionTree; +import org.sonar.plugins.php.api.tree.expression.ExpressionTree; +import org.sonar.plugins.php.api.tree.expression.VariableIdentifierTree; import org.sonar.plugins.php.api.tree.statement.*; import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -44,107 +49,237 @@ public class AvoidMultipleIfElseStatementCheck extends PHPSubscriptionCheck { public static final String RULE_KEY = "EC2"; public static final String ERROR_MESSAGE = "Use a switch statement instead of multiple if-else if possible"; - public static final int INDEX_NOT_FOUND = -1; + + private static final Logger LOGGER = Loggers.get(AvoidMultipleIfElseStatementCheck.class); + + private static final VariablesPerLevelDataStructure variablesStruct = new VariablesPerLevelDataStructure(); @Override public List nodesToVisit() { - return List.of(Kind.IF_STATEMENT, Kind.ELSEIF_CLAUSE, Kind.ELSE_CLAUSE); + return List.of(Kind.METHOD_DECLARATION); } @Override public void visitNode(Tree tree) { - Tree parentNode = tree.getParent(); - if ( ! (parentNode instanceof BlockTree)) { - return; - } - visitConditionalNodes(0, new VariablesPerLevelDataStructure()); + MethodDeclarationTree method = (MethodDeclarationTree)tree; -// checkIfStatementAtTheSameLevel(tree); -// checkElseIfStatement(tree); - } + if (!method.body().is(Kind.BLOCK)) { + return; + } - private void visitConditionalNodes(int level, VariablesPerLevelDataStructure parentDataMap) { + visitNodeContent(((BlockTree) method.body()).statements(), 0); } - private void checkIfStatementAtTheSameLevel(Tree tree) { - int countIfStatement = 0; - - Tree parentNode = tree.getParent(); - if (!(parentNode instanceof BlockTree)) { + private void visitNodeContent(List lstStatements, int pLevel) { + if (lstStatements == null || lstStatements.isEmpty()) { return; } - // getting parent bloc to count if several IF at the same level - BlockTree node = (BlockTree) parentNode; - int sizeBody = node.statements().size(); - for(int i=0; i 1){ - context().newIssue(this, tree, ERROR_MESSAGE); - } } - private void checkElseIfStatement(Tree tree) { - String ifTree = tree.toString(); - String findStr = "elseif"; - int count = countMatches(ifTree, findStr); - if (count >= 2) { - context().newIssue(this, tree, ERROR_MESSAGE); - } + private void visitIfNode(IfStatementTree pIfTree, int pLevel) { + // analyse variables and raise error if neede + analyseVariables(pIfTree, pLevel); + + // go to next child level + visitNodeContent(pIfTree.statements(), pLevel + 1); } - public static int countMatches(String str, String sub) { - if (isBlankString(str) || isBlankString(sub)) { - return 0; + private void analyseVariables(IfStatementTree pIfTree, int pLevel) { + ExpressionTree expr = pIfTree.condition().expression(); + LOGGER.debug(expr.toString()); + + if (expr instanceof BinaryExpressionTree) { + analyseVariables((BinaryExpressionTree) expr, pLevel); } - int count = 0; - int idx = 0; - while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) { - count++; - idx += sub.length(); + + } + + private void analyseVariables(BinaryExpressionTree pBinExprTree, int pLevel) { + if (pBinExprTree.is(Kind.EQUAL_TO) + || pBinExprTree.is(Kind.NOT_EQUAL_TO) + || pBinExprTree.is(Kind.GREATER_THAN_OR_EQUAL_TO) + || pBinExprTree.is(Kind.LESS_THAN_OR_EQUAL_TO)) { + if (pBinExprTree.leftOperand().is(Kind.VARIABLE_IDENTIFIER)) { + analyseVariables((VariableIdentifierTree) pBinExprTree.leftOperand(), pLevel); + } + if (pBinExprTree.rightOperand().is(Kind.VARIABLE_IDENTIFIER)) { + analyseVariables((VariableIdentifierTree) pBinExprTree.rightOperand(), pLevel); + } + } else if (pBinExprTree.is(Kind.CONDITIONAL_AND) || pBinExprTree.is(Kind.CONDITIONAL_OR)) { + analyseVariables((BinaryExpressionTree) pBinExprTree.leftOperand(), pLevel); + analyseVariables((BinaryExpressionTree) pBinExprTree.rightOperand(), pLevel); } - return count; } - public static boolean isBlankString(String str) { - return str == null || str.isBlank(); + private void analyseVariables(VariableIdentifierTree pVarIdTree, int pLevel) { + if (pVarIdTree.variableExpression().is(Kind.VARIABLE_IDENTIFIER)) { + int nbUsed = variablesStruct.incrementVariableUsageForLevel(pVarIdTree.text(), pLevel); + + // raise an error if maximum + if (nbUsed > 2) { + context().newIssue(this, pVarIdTree, ERROR_MESSAGE); + } + } } - private class VariablesPerLevelDataStructure { - /* - Map> ==> - - Key : index of Level (1 = first level) - - Value : Map - - Key : name of variable in the current level - - Value : number of usage of this variable in a IF statement in current level or one of parent levels - */ +// private void checkIfStatementAtTheSameLevel(Tree tree) { +// int countIfStatement = 0; +// +// Tree parentNode = tree.getParent(); +// if (!(parentNode instanceof BlockTree)) { +// return; +// } +// +// // getting parent bloc to count if several IF at the same level +// BlockTree node = (BlockTree) parentNode; +// int sizeBody = node.statements().size(); +// for (int i = 0; i < sizeBody; ++i) { +// if (node.statements().get(i) instanceof IfStatementTree) { +// ++countIfStatement; +// } +// } +// if (countIfStatement > 1) { +// context().newIssue(this, tree, ERROR_MESSAGE); +// } +// } +// +// private void checkElseIfStatement(Tree tree) { +// String ifTree = tree.toString(); +// String findStr = "elseif"; +// int count = countMatches(ifTree, findStr); +// if (count >= 2) { +// context().newIssue(this, tree, ERROR_MESSAGE); +// } +// } +// +// public static int countMatches(String str, String sub) { +// if (isBlankString(str) || isBlankString(sub)) { +// return 0; +// } +// int count = 0; +// int idx = 0; +// while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) { +// count++; +// idx += sub.length(); +// } +// return count; +// } +// +// public static boolean isBlankString(String str) { +// return str == null || str.isBlank(); +// } + + /** + * Complex data structure representing variables count per AST level (cumulative count with parent levels) + * Map> ==> + * - Key : index of Level (0 = first level) + * - Value : Map + * - Key : name of variable in the current or parent level + * - Value : number of usage of this variable in a IF statement in current level or one of parent levels + * + */ + private static class VariablesPerLevelDataStructure { + private final Map> mapVariablesPerLevel; public VariablesPerLevelDataStructure() { mapVariablesPerLevel = new HashMap<>(10); } - public VariablesPerLevelDataStructure(Map> pMapVariablesPerLevel) { - mapVariablesPerLevel = Map.copyOf(pMapVariablesPerLevel); + public VariablesPerLevelDataStructure(Map> pParentLevelMap) { + mapVariablesPerLevel = Map.copyOf(pParentLevelMap); } - public void incrementUsageForVariableForLevel(String variableName, int level) { + public int incrementVariableUsageForLevel(String variableName, int pLevel) { - // variables map initilization if absent - Map mapVariables = mapVariablesPerLevel.computeIfAbsent(level, k -> new HashMap<>(5)); + // get variable usage map for current level + Map variablesMap = mapVariablesPerLevel.get(pLevel); + if (variablesMap == null) { + variablesMap = new HashMap<>(5); + mapVariablesPerLevel.put(pLevel, variablesMap); + } - Integer nbUsed = mapVariables.get(variableName); + // get usage from parent if needed + Integer nbUsed = variablesMap.get(variableName); if (nbUsed == null) { - nbUsed = 0; + Integer nbParentUsed = getVariableUsageOfNearestParent(variableName, pLevel - 1); + nbUsed = nbParentUsed == null ? 0 : nbParentUsed; } + + // increment usage for current level nbUsed++; - mapVariables.put(variableName, nbUsed); + variablesMap.put(variableName, nbUsed); + + return nbUsed; } + + private Integer getVariableUsageOfNearestParent(String variableName, int pLevel) { + + Integer nbParentUsed = null; + for (int i = pLevel; i >= 0 && nbParentUsed == null; i--) { + Map variablesParentLevelMap = mapVariablesPerLevel.get(i); + nbParentUsed = variablesParentLevelMap.get(variableName); + } + + return nbParentUsed; + } + +// private Map initializeAndOrGetVariablesMap(int pLevel) { +// +// Map variablesMap = mapVariablesPerLevel.get(pLevel); +// if (variablesMap == null) { +// // getting variables map from parent level to copy to current level if initialization needed +// Map variablesParentLevelMap = mapVariablesPerLevel.get(pLevel - 1); +// } +// +// +// // getting variables map from parent level to copy to current level if initialization needed +// Map variablesParentLevelMap = mapVariablesPerLevel.get(pLevel - 1); +// +// Map variablesMap = mapVariablesPerLevel.computeIfAbsent(pLevel, k -> new HashMap<>(5)); +// +// // variables map initialization : create empty HashMap if needed +// if (variablesParentLevelMap != null && !variablesParentLevelMap.isEmpty() && !variablesMap.isEmpty()) { +// for (Map.Entry entry : variablesParentLevelMap.entrySet()) { +// variablesMap.putIfAbsent(entry.getKey(), entry.getValue()); +// } +// } +// +// return variablesMap; +// } +// +// private void incrementVariableUsageForExistingChildLevels(String variableName, int level) { +// +// // variables map initilization if absent +// Map mapVariables = mapVariablesPerLevel.computeIfAbsent(level, k -> new HashMap<>(5)); +// +// Integer nbUsed = mapVariables.get(variableName); +// if (nbUsed == null) { +// nbUsed = 0; +// } +// nbUsed++; +// mapVariables.put(variableName, nbUsed); +// } } } diff --git a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php index e868eb1b6..1bf994e8c 100644 --- a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php +++ b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php @@ -12,29 +12,30 @@ class AvoidMultipleIfElseStatement ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // COMPLIANT - // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements - // at the same level AND no problem with several IF staments at the same level using different variables - public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsed() - { - $nb1 = 0; - $nb2 = 0; - - if ($nb1 == 1) { - $nb1 = 1; - } else { - $nb2 = 2; - } - - if ($nb2 == 2) { - $nb1 = 3; - } else { - $nb1 = 4; - } - - return $nb1; - } - +// // COMPLIANT +// // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements +// // at the same level AND no problem with several IF staments at the same level using different variables +// public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsed() +// { +// $nb1 = 0; +// $nb2 = 0; +// $nb3 = 0; +// +// if ($nb3 == 1 && $nb1 == 1) { +// $nb1 = 1; +// } else { +// $nb2 = 2; +// } +// +// if ($nb2 == 2) { +// $nb1 = 3; +// } else { +// $nb1 = 4; +// } +// +// return $nb1; +// } +// // // COMPLIANT // // USE CASE : compliant use case to check if one variable is used maximum twice in different IF statements // public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInIfStatements() @@ -159,7 +160,7 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa // $nb1 = 0; // $nb2 = 0; // -// if ($nb1 == 1) { // NOK {{Use a switch statement instead of multiple if-else if possible}} +// if ($nb1 == 1) { // $nb1 = 1; // } else { // $nb2 = 2; @@ -171,28 +172,28 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa // // return $nb1; // } -// -// // NON COMPLIANT -// // USE CASE : NON compliant use case to check if following is NOT OK : -// // - same variable used maximum twice : no beause 2 IFs and 1 ELSE -// public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInIfStatementsAtDifferentsLevels() -// { -// $nb1 = 0; -// $nb2 = 0; -// -// if ($nb1 == 1) { -// if ($nb1 == 2) { -// $nb1 = 1; -// } else { -// $nb2 = 3; -// } -// } else { -// $nb2 = 2; -// } -// -// return $nb1; -// } -// + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT OK : + // - same variable used maximum twice : no compliant because 2 IFs and 1 ELSE + public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInIfStatementsAtDifferentsLevels() + { + $nb1 = 0; + $nb2 = 0; + + if ($nb1 == 1) { + if ($nb1 == 2) { + $nb1 = 1; + } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb2 = 3; + } + } else { + $nb2 = 2; + } + + return $nb1; + } + // // NON COMPLIANT // // USE CASE : non compliant use case to check if following is NOT OK : // // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE @@ -207,7 +208,7 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa // } else { // if ($nb1 == 2) { // $nb1 = 1; -// } else { +// } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} // $nb2 = 3; // } // } @@ -224,15 +225,15 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa // $nb1 = 0; // $nb2 = 0; // -// if ($nb1 == 1) { // NOK {{Use a switch statement instead of multiple if-else if possible}} +// if ($nb1 == 1) { // $nb2 = 2; // } else { -// if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} +// if ($nb1 == 2) { // $nb1 = 1; -// } else { +// } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} // if ($nb1 == 3) { // NOK {{Use a switch statement instead of multiple if-else if possible}} // $nb1 = 4; -// } else { +// } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} // $nb2 = 5; // } // } @@ -251,11 +252,11 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa // $nb2 = 10; // $nb3 = 11; // -// if ($nb1 == 1) { // NOK {{Use a switch statement instead of multiple if-else if possible}} +// if ($nb1 == 1) { // $nb2 = 1; -// } elseif ($nb1 == $nb2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} +// } elseif ($nb1 == $nb2) { // $nb2 = 2; -// } else { +// } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} // $nb2 = 4; // } // @@ -272,13 +273,13 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa // $nb2 = 10; // $nb3 = 11; // -// if ($nb1 == 1) { // NOK {{Use a switch statement instead of multiple if-else if possible}} +// if ($nb1 == 1) { // $nb2 = 1; -// } elseif ($nb1 == $nb2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} +// } elseif ($nb1 == $nb2) { // $nb2 = 2; // } elseif ($nb3 == $nb1) { // NOK {{Use a switch statement instead of multiple if-else if possible}} // $nb2 = 3; -// } else { +// } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} // $nb2 = 4; // } // From dc73ed5ba0b4d0b7a5b30cd7bcca68906725fad6 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 21 Jul 2023 23:12:12 +0700 Subject: [PATCH 127/170] [ISSUE 121] refactoring use case multiple-if-else - TER --- .../AvoidMultipleIfElseStatementCheck.java | 102 +++++++++++++----- .../checks/AvoidMultipleIfElseStatement.php | 2 +- 2 files changed, 78 insertions(+), 26 deletions(-) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java index 103b0983e..6717e6430 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -38,6 +38,11 @@ /** * functional description : please see HTML description file of this rule (resources directory) + * technical choices : + * - Kind.IF_STATEMENT, Kind.ELSE_STATEMENT, Kind.ELSEIF_STATEMENT because it isn't possible + * to keep parent references to check later if variables already used or not in parent tree + * - only one way to keep parent history : manually go throw the all tree and thus, start at method declaration + * */ @Rule( key = AvoidMultipleIfElseStatementCheck.RULE_KEY, @@ -78,18 +83,18 @@ private void visitNodeContent(List lstStatements, int pLevel) { } for (StatementTree statement : lstStatements) { - if (statement.is(Kind.IF_STATEMENT)) { + if (statement.is(Kind.BLOCK)) { + LOGGER.debug("BLOCK node - go to child nodes : {}", statement.toString()); + visitNodeContent(((BlockTree)statement).statements(), pLevel); // Block Statement is not a new LEVEL + } else if (statement.is(Kind.IF_STATEMENT)) { LOGGER.debug("Visiting IF_STATEMENT node : {}", statement.toString()); visitIfNode((IfStatementTree)statement, pLevel); - } else if (statement.is(Kind.ELSEIF_CLAUSE)) { - LOGGER.debug("Visiting ELSEIF_CLAUSE node : {}", statement.toString()); - // TODO DDC - } else if (statement.is(Kind.ELSE_CLAUSE)) { - LOGGER.debug("Visiting ELSE_CLAUSE node : {}", statement.toString()); - // TODO DDC - } else if (statement.is(Kind.BLOCK)) { - LOGGER.debug("NO node visit because of incompatibility : {}", statement.toString()); - visitNodeContent(((BlockTree)statement).statements(), pLevel); // Block Statement is not a new LEVEL +// } else if (statement.is(Kind.ELSEIF_CLAUSE)) { +// LOGGER.debug("Visiting ELSEIF_CLAUSE node : {}", statement.toString()); +// // TODO DDC +// } else if (statement.is(Kind.ELSE_CLAUSE)) { +// LOGGER.debug("Visiting ELSE_CLAUSE node : {}", statement.toString()); +// visitElseNode((ElseClauseTree)statement, pLevel); } else { LOGGER.debug("NO node visit because of incompatibility : {}", statement.toString()); } @@ -97,41 +102,84 @@ private void visitNodeContent(List lstStatements, int pLevel) { } private void visitIfNode(IfStatementTree pIfTree, int pLevel) { - // analyse variables and raise error if neede - analyseVariables(pIfTree, pLevel); - // go to next child level + if (pIfTree == null) return; + + // analyze condition variables and raise error if needed + analyzeConditionVariables(pIfTree, pLevel); + + // analyze ELSE clause + visitElseNode(pIfTree.elseClause(), pLevel); + + // TODO DDC + // analyze ELSEIF clauses +// if (pIfTree.elseifClauses() != null && !pIfTree.elseifClauses().isEmpty()) { +// for (ElseifClauseTree elseifClause : pIfTree.elseifClauses()) { +// visitElseIfNode(elseifClause, pLevel); +// } +// } + + // go to next child level of if statement visitNodeContent(pIfTree.statements(), pLevel + 1); } - private void analyseVariables(IfStatementTree pIfTree, int pLevel) { - ExpressionTree expr = pIfTree.condition().expression(); - LOGGER.debug(expr.toString()); + private void analyzeConditionVariables(IfStatementTree pIfTree, int pLevel) { + if (pIfTree.condition() == null) return; + + ExpressionTree expr = pIfTree.condition().expression(); if (expr instanceof BinaryExpressionTree) { - analyseVariables((BinaryExpressionTree) expr, pLevel); + analyzeConditionVariables((BinaryExpressionTree) expr, pLevel); + } + + } + + private void visitElseNode(ElseClauseTree pElseTree, int pLevel) { + // analyze variables and raise error if needed + analyzeVariables(pElseTree, pLevel); + + // go to next child level + visitNodeContent(pElseTree.statements(), pLevel + 1); + } + + private void analyzeVariables(ElseClauseTree pElseTree, int pLevel) { + + for (Map.Entry entry : variablesStruct.getVariables(pLevel).entrySet()) { + String variableName = entry.getKey(); + + // increment usage of all varibales in the same level of ELSE staetement + int nbUsed = variablesStruct.incrementVariableUsageForLevel(variableName, pLevel); + + // raise an error if maximum + if (nbUsed > 2) { + context().newIssue(this, pElseTree, ERROR_MESSAGE); + } } } - private void analyseVariables(BinaryExpressionTree pBinExprTree, int pLevel) { - if (pBinExprTree.is(Kind.EQUAL_TO) + private void analyzeConditionVariables(BinaryExpressionTree pBinExprTree, int pLevel) { + if (pBinExprTree.is(Kind.CONDITIONAL_AND) || pBinExprTree.is(Kind.CONDITIONAL_OR)) { + if (pBinExprTree.leftOperand() instanceof BinaryExpressionTree) { + analyzeConditionVariables((BinaryExpressionTree) pBinExprTree.leftOperand(), pLevel); + } + if (pBinExprTree.rightOperand() instanceof BinaryExpressionTree) { + analyzeConditionVariables((BinaryExpressionTree) pBinExprTree.rightOperand(), pLevel); + } + } else if (pBinExprTree.is(Kind.EQUAL_TO) || pBinExprTree.is(Kind.NOT_EQUAL_TO) || pBinExprTree.is(Kind.GREATER_THAN_OR_EQUAL_TO) || pBinExprTree.is(Kind.LESS_THAN_OR_EQUAL_TO)) { if (pBinExprTree.leftOperand().is(Kind.VARIABLE_IDENTIFIER)) { - analyseVariables((VariableIdentifierTree) pBinExprTree.leftOperand(), pLevel); + analyzeVariables((VariableIdentifierTree) pBinExprTree.leftOperand(), pLevel); } if (pBinExprTree.rightOperand().is(Kind.VARIABLE_IDENTIFIER)) { - analyseVariables((VariableIdentifierTree) pBinExprTree.rightOperand(), pLevel); + analyzeVariables((VariableIdentifierTree) pBinExprTree.rightOperand(), pLevel); } - } else if (pBinExprTree.is(Kind.CONDITIONAL_AND) || pBinExprTree.is(Kind.CONDITIONAL_OR)) { - analyseVariables((BinaryExpressionTree) pBinExprTree.leftOperand(), pLevel); - analyseVariables((BinaryExpressionTree) pBinExprTree.rightOperand(), pLevel); } } - private void analyseVariables(VariableIdentifierTree pVarIdTree, int pLevel) { + private void analyzeVariables(VariableIdentifierTree pVarIdTree, int pLevel) { if (pVarIdTree.variableExpression().is(Kind.VARIABLE_IDENTIFIER)) { int nbUsed = variablesStruct.incrementVariableUsageForLevel(pVarIdTree.text(), pLevel); @@ -244,6 +292,10 @@ private Integer getVariableUsageOfNearestParent(String variableName, int pLevel) return nbParentUsed; } + public Map getVariables(int pLevel) { + return mapVariablesPerLevel.get(pLevel); + } + // private Map initializeAndOrGetVariablesMap(int pLevel) { // // Map variablesMap = mapVariablesPerLevel.get(pLevel); diff --git a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php index 1bf994e8c..500628cc5 100644 --- a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php +++ b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php @@ -182,7 +182,7 @@ public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInIfStatemen $nb2 = 0; if ($nb1 == 1) { - if ($nb1 == 2) { + if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} $nb1 = 1; } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} $nb2 = 3; From 328a69704bcaa6dd9f6fb0561df51db65302c381 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sun, 23 Jul 2023 22:22:55 +0700 Subject: [PATCH 128/170] [ISSUE 121] refactoring use case multiple-if-else : else + elsif NON compliant uses cases OK --- .../AvoidMultipleIfElseStatementCheck.java | 51 +++- .../checks/AvoidMultipleIfElseStatement.php | 270 ++++++++++-------- 2 files changed, 192 insertions(+), 129 deletions(-) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java index 6717e6430..6abca0e96 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -39,9 +39,10 @@ /** * functional description : please see HTML description file of this rule (resources directory) * technical choices : - * - Kind.IF_STATEMENT, Kind.ELSE_STATEMENT, Kind.ELSEIF_STATEMENT because it isn't possible + * - Kind.IF_STATEMENT, Kind.ELSE_STATEMENT, Kind.ELSEIF_STATEMENT not used because it isn't possible * to keep parent references to check later if variables already used or not in parent tree * - only one way to keep parent history : manually go throw the all tree and thus, start at method declaration + * - an "ELSE" statement is considered as a second IF statement using the same variables tests * */ @Rule( @@ -57,7 +58,7 @@ public class AvoidMultipleIfElseStatementCheck extends PHPSubscriptionCheck { private static final Logger LOGGER = Loggers.get(AvoidMultipleIfElseStatementCheck.class); - private static final VariablesPerLevelDataStructure variablesStruct = new VariablesPerLevelDataStructure(); + private static VariablesPerLevelDataStructure variablesStruct = new VariablesPerLevelDataStructure(); @Override public List nodesToVisit() { @@ -73,6 +74,9 @@ public void visitNode(Tree tree) { return; } + // reinit data structure before each method analysis + variablesStruct = new VariablesPerLevelDataStructure(); + visitNodeContent(((BlockTree) method.body()).statements(), 0); } @@ -108,17 +112,16 @@ private void visitIfNode(IfStatementTree pIfTree, int pLevel) { // analyze condition variables and raise error if needed analyzeConditionVariables(pIfTree, pLevel); + // analyze ELSEIF clauses + if (pIfTree.elseifClauses() != null && !pIfTree.elseifClauses().isEmpty()) { + for (ElseifClauseTree elseifClause : pIfTree.elseifClauses()) { + visitElseIfNode(elseifClause, pLevel); + } + } + // analyze ELSE clause visitElseNode(pIfTree.elseClause(), pLevel); - // TODO DDC - // analyze ELSEIF clauses -// if (pIfTree.elseifClauses() != null && !pIfTree.elseifClauses().isEmpty()) { -// for (ElseifClauseTree elseifClause : pIfTree.elseifClauses()) { -// visitElseIfNode(elseifClause, pLevel); -// } -// } - // go to next child level of if statement visitNodeContent(pIfTree.statements(), pLevel + 1); } @@ -135,6 +138,9 @@ private void analyzeConditionVariables(IfStatementTree pIfTree, int pLevel) { } private void visitElseNode(ElseClauseTree pElseTree, int pLevel) { + + if (pElseTree == null) { return; } + // analyze variables and raise error if needed analyzeVariables(pElseTree, pLevel); @@ -155,7 +161,32 @@ private void analyzeVariables(ElseClauseTree pElseTree, int pLevel) { context().newIssue(this, pElseTree, ERROR_MESSAGE); } } + } + + private void visitElseIfNode(ElseifClauseTree pElseIfTree, int pLevel) { + + if (pElseIfTree == null) { return; } + + // analyze variables and raise error if needed + analyzeVariables(pElseIfTree, pLevel); + + // go to next child level + visitNodeContent(pElseIfTree.statements(), pLevel + 1); + } + + private void analyzeVariables(ElseifClauseTree pElseIfTree, int pLevel) { + + for (Map.Entry entry : variablesStruct.getVariables(pLevel).entrySet()) { + String variableName = entry.getKey(); + // increment usage of all varibales in the same level of ELSE staetement + int nbUsed = variablesStruct.incrementVariableUsageForLevel(variableName, pLevel); + + // raise an error if maximum + if (nbUsed > 2) { + context().newIssue(this, pElseIfTree, ERROR_MESSAGE); + } + } } private void analyzeConditionVariables(BinaryExpressionTree pBinExprTree, int pLevel) { diff --git a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php index 500628cc5..7c18815f7 100644 --- a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php +++ b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php @@ -12,30 +12,62 @@ class AvoidMultipleIfElseStatement ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // COMPLIANT + // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements + // at the same level AND no problem with several IF staments at the same level using different variables + public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsed() + { + $nb1 = 0; + $nb2 = 0; + $nb3 = 0; + + if ($nb3 == 1 && $nb1 == 1) { + $nb1 = 1; + } else { + $nb2 = 2; + } + + if ($nb2 == 2) { + $nb1 = 3; + } else { + $nb1 = 4; + } + + return $nb1; + } + // // COMPLIANT // // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements // // at the same level AND no problem with several IF staments at the same level using different variables -// public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsed() +// public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsedAtDifferentLevels() // { // $nb1 = 0; // $nb2 = 0; // $nb3 = 0; // -// if ($nb3 == 1 && $nb1 == 1) { -// $nb1 = 1; +// if ($nb1 == 1) { +// if ($nb2 == 2) { +// $nb1 = 3; +// } else { +// $nb1 = 4; +// } // } else { // $nb2 = 2; // } // -// if ($nb2 == 2) { -// $nb1 = 3; +// if ($nb3 == 1) { +// if ($nb2 == 2) { +// $nb1 = 3; +// } else { +// $nb1 = 4; +// } // } else { -// $nb1 = 4; +// $nb2 = 2; // } // // return $nb1; // } -// + // // COMPLIANT // // USE CASE : compliant use case to check if one variable is used maximum twice in different IF statements // public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInIfStatements() @@ -151,27 +183,27 @@ class AvoidMultipleIfElseStatement // // // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// // NON COMPLIANT -// // USE CASE : NON compliant use case to check if following is NOT COMPLIANT : -// // one variable is used maximum in two IF / ELSE / ELSEIF statements -// public function shouldBeNotCompliantBecauseVariablesIsUsedMoreThanTwice() -// { -// $nb1 = 0; -// $nb2 = 0; -// -// if ($nb1 == 1) { -// $nb1 = 1; -// } else { -// $nb2 = 2; -// } -// -// if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} -// $nb2 = 3; -// } -// -// return $nb1; -// } + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT COMPLIANT : + // one variable is used maximum in two IF / ELSE / ELSEIF statements + public function shouldBeNotCompliantBecauseVariablesIsUsedMoreThanTwice() + { + $nb1 = 0; + $nb2 = 0; + + if ($nb1 == 1) { + $nb1 = 1; + } else { + $nb2 = 2; + } + + if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb2 = 3; + } + + return $nb1; + } // NON COMPLIANT // USE CASE : NON compliant use case to check if following is NOT OK : @@ -194,96 +226,96 @@ public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInIfStatemen return $nb1; } -// // NON COMPLIANT -// // USE CASE : non compliant use case to check if following is NOT OK : -// // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE -// // - usage of the same variable on different levels of IF statements -// public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatements() -// { -// $nb1 = 0; -// $nb2 = 0; -// -// if ($nb1 == 1) { -// $nb2 = 2; -// } else { -// if ($nb1 == 2) { -// $nb1 = 1; -// } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} -// $nb2 = 3; -// } -// } -// -// return $nb1; -// } -// -// // NON COMPLIANT -// // USE CASE : NON compliant use case to check if following is NOT OK : -// // - the same variable must used maximum twice -// // - usage of the same variable on different levels of IF / ELSE statements -// public function shouldBeNotCompliantBecauseVariableUsedMaximumTwiceInComposedElseStatements() -// { -// $nb1 = 0; -// $nb2 = 0; -// -// if ($nb1 == 1) { -// $nb2 = 2; -// } else { -// if ($nb1 == 2) { -// $nb1 = 1; -// } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} -// if ($nb1 == 3) { // NOK {{Use a switch statement instead of multiple if-else if possible}} -// $nb1 = 4; -// } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} -// $nb2 = 5; -// } -// } -// } -// -// return $nb1; -// } -// -// // NON COMPLIANT -// // USE CASE : NON compliant use case to check if following is NOT OK : -// // - more than twice uses of the same variable -// // - usage of the same variable on different kind of test statements (IF and ELSEIF) -// public function shouldBeNotCompliantBecauseTheSameVariableIsUsedMoreThanTwice() // NOT Compliant -// { -// $nb1 = 0; -// $nb2 = 10; -// $nb3 = 11; -// -// if ($nb1 == 1) { -// $nb2 = 1; -// } elseif ($nb1 == $nb2) { -// $nb2 = 2; -// } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} -// $nb2 = 4; -// } -// -// return $nb2; -// } -// -// // NON COMPLIANT -// // USE CASE : NON compliant use case to check if following is NOT OK : -// // - more than twice uses of the same variable -// // - usage of the same variable on different kind of test statements (IF and ELSEIF) -// public function shouldBeNotCompliantBecauseTheSameVariableIsUsedManyTimes() // NOT Compliant -// { -// $nb1 = 0; -// $nb2 = 10; -// $nb3 = 11; -// -// if ($nb1 == 1) { -// $nb2 = 1; -// } elseif ($nb1 == $nb2) { -// $nb2 = 2; -// } elseif ($nb3 == $nb1) { // NOK {{Use a switch statement instead of multiple if-else if possible}} -// $nb2 = 3; -// } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} -// $nb2 = 4; -// } -// -// return $nb2; -// } + // NON COMPLIANT + // USE CASE : non compliant use case to check if following is NOT OK : + // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE + // - usage of the same variable on different levels of IF statements + public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatements() + { + $nb1 = 0; + $nb2 = 0; + + if ($nb1 == 1) { + $nb2 = 2; + } else { + if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb1 = 1; + } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb2 = 3; + } + } + + return $nb1; + } + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT OK : + // - the same variable must used maximum twice + // - usage of the same variable on different levels of IF / ELSE statements + public function shouldBeNotCompliantBecauseVariableUsedMaximumTwiceInComposedElseStatements() + { + $nb1 = 0; + $nb2 = 0; + + if ($nb1 == 1) { + $nb2 = 2; + } else { + if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb1 = 1; + } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} + if ($nb1 == 3) { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb1 = 4; + } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb2 = 5; + } + } + } + + return $nb1; + } + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT OK : + // - more than twice uses of the same variable + // - usage of the same variable on different kind of test statements (IF and ELSEIF) + public function shouldBeNotCompliantBecauseTheSameVariableIsUsedMoreThanTwice() // NOT Compliant + { + $nb1 = 0; + $nb2 = 10; + $nb3 = 11; + + if ($nb1 == 1) { + $nb2 = 1; + } elseif ($nb1 == $nb2) { + $nb2 = 2; + } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb2 = 4; + } + + return $nb2; + } + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT OK : + // - more than twice uses of the same variable + // - usage of the same variable on different kind of test statements (IF and ELSEIF) + public function shouldBeNotCompliantBecauseTheSameVariableIsUsedManyTimes() // NOT Compliant + { + $nb1 = 0; + $nb2 = 10; + $nb3 = 11; + + if ($nb1 == 1) { + $nb2 = 1; + } elseif ($nb1 == $nb2) { + $nb2 = 2; + } elseif ($nb3 == $nb1) { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb2 = 3; + } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb2 = 4; + } + + return $nb2; + } } From d5126aa587a819ccaa618496ee66962bcc85536a Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sun, 23 Jul 2023 22:44:32 +0700 Subject: [PATCH 129/170] [ISSUE 121] refactoring use case multiple-if-else : refacto method names + elsif use case --- .../AvoidMultipleIfElseStatementCheck.java | 110 ++++++++---------- 1 file changed, 50 insertions(+), 60 deletions(-) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java index 6abca0e96..7817d4069 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -93,12 +93,6 @@ private void visitNodeContent(List lstStatements, int pLevel) { } else if (statement.is(Kind.IF_STATEMENT)) { LOGGER.debug("Visiting IF_STATEMENT node : {}", statement.toString()); visitIfNode((IfStatementTree)statement, pLevel); -// } else if (statement.is(Kind.ELSEIF_CLAUSE)) { -// LOGGER.debug("Visiting ELSEIF_CLAUSE node : {}", statement.toString()); -// // TODO DDC -// } else if (statement.is(Kind.ELSE_CLAUSE)) { -// LOGGER.debug("Visiting ELSE_CLAUSE node : {}", statement.toString()); -// visitElseNode((ElseClauseTree)statement, pLevel); } else { LOGGER.debug("NO node visit because of incompatibility : {}", statement.toString()); } @@ -110,7 +104,7 @@ private void visitIfNode(IfStatementTree pIfTree, int pLevel) { if (pIfTree == null) return; // analyze condition variables and raise error if needed - analyzeConditionVariables(pIfTree, pLevel); + computeConditionVariables(pIfTree, pLevel); // analyze ELSEIF clauses if (pIfTree.elseifClauses() != null && !pIfTree.elseifClauses().isEmpty()) { @@ -126,39 +120,45 @@ private void visitIfNode(IfStatementTree pIfTree, int pLevel) { visitNodeContent(pIfTree.statements(), pLevel + 1); } - private void analyzeConditionVariables(IfStatementTree pIfTree, int pLevel) { + private void computeConditionVariables(IfStatementTree pIfTree, int pLevel) { if (pIfTree.condition() == null) return; ExpressionTree expr = pIfTree.condition().expression(); if (expr instanceof BinaryExpressionTree) { - analyzeConditionVariables((BinaryExpressionTree) expr, pLevel); + computeConditionVariables((BinaryExpressionTree) expr, pLevel); } } - private void visitElseNode(ElseClauseTree pElseTree, int pLevel) { - - if (pElseTree == null) { return; } - - // analyze variables and raise error if needed - analyzeVariables(pElseTree, pLevel); - - // go to next child level - visitNodeContent(pElseTree.statements(), pLevel + 1); + private void computeConditionVariables(BinaryExpressionTree pBinExprTree, int pLevel) { + if (pBinExprTree.is(Kind.CONDITIONAL_AND) || pBinExprTree.is(Kind.CONDITIONAL_OR)) { + if (pBinExprTree.leftOperand() instanceof BinaryExpressionTree) { + computeConditionVariables((BinaryExpressionTree) pBinExprTree.leftOperand(), pLevel); + } + if (pBinExprTree.rightOperand() instanceof BinaryExpressionTree) { + computeConditionVariables((BinaryExpressionTree) pBinExprTree.rightOperand(), pLevel); + } + } else if (pBinExprTree.is(Kind.EQUAL_TO) + || pBinExprTree.is(Kind.NOT_EQUAL_TO) + || pBinExprTree.is(Kind.GREATER_THAN_OR_EQUAL_TO) + || pBinExprTree.is(Kind.LESS_THAN_OR_EQUAL_TO)) { + if (pBinExprTree.leftOperand().is(Kind.VARIABLE_IDENTIFIER)) { + computeVariables((VariableIdentifierTree) pBinExprTree.leftOperand(), pLevel); + } + if (pBinExprTree.rightOperand().is(Kind.VARIABLE_IDENTIFIER)) { + computeVariables((VariableIdentifierTree) pBinExprTree.rightOperand(), pLevel); + } + } } - private void analyzeVariables(ElseClauseTree pElseTree, int pLevel) { - - for (Map.Entry entry : variablesStruct.getVariables(pLevel).entrySet()) { - String variableName = entry.getKey(); - - // increment usage of all varibales in the same level of ELSE staetement - int nbUsed = variablesStruct.incrementVariableUsageForLevel(variableName, pLevel); + private void computeVariables(VariableIdentifierTree pVarIdTree, int pLevel) { + if (pVarIdTree.variableExpression().is(Kind.VARIABLE_IDENTIFIER)) { + int nbUsed = variablesStruct.incrementVariableUsageForLevel(pVarIdTree.text(), pLevel); // raise an error if maximum if (nbUsed > 2) { - context().newIssue(this, pElseTree, ERROR_MESSAGE); + context().newIssue(this, pVarIdTree, ERROR_MESSAGE); } } } @@ -168,55 +168,45 @@ private void visitElseIfNode(ElseifClauseTree pElseIfTree, int pLevel) { if (pElseIfTree == null) { return; } // analyze variables and raise error if needed - analyzeVariables(pElseIfTree, pLevel); + computeConditionVariables(pElseIfTree, pLevel); // go to next child level visitNodeContent(pElseIfTree.statements(), pLevel + 1); } - private void analyzeVariables(ElseifClauseTree pElseIfTree, int pLevel) { + private void computeConditionVariables(ElseifClauseTree pElseIfTree, int pLevel) { - for (Map.Entry entry : variablesStruct.getVariables(pLevel).entrySet()) { - String variableName = entry.getKey(); - - // increment usage of all varibales in the same level of ELSE staetement - int nbUsed = variablesStruct.incrementVariableUsageForLevel(variableName, pLevel); + if (pElseIfTree.condition() == null) return; - // raise an error if maximum - if (nbUsed > 2) { - context().newIssue(this, pElseIfTree, ERROR_MESSAGE); - } + ExpressionTree expr = pElseIfTree.condition().expression(); + if (expr instanceof BinaryExpressionTree) { + computeConditionVariables((BinaryExpressionTree) expr, pLevel); } + } - private void analyzeConditionVariables(BinaryExpressionTree pBinExprTree, int pLevel) { - if (pBinExprTree.is(Kind.CONDITIONAL_AND) || pBinExprTree.is(Kind.CONDITIONAL_OR)) { - if (pBinExprTree.leftOperand() instanceof BinaryExpressionTree) { - analyzeConditionVariables((BinaryExpressionTree) pBinExprTree.leftOperand(), pLevel); - } - if (pBinExprTree.rightOperand() instanceof BinaryExpressionTree) { - analyzeConditionVariables((BinaryExpressionTree) pBinExprTree.rightOperand(), pLevel); - } - } else if (pBinExprTree.is(Kind.EQUAL_TO) - || pBinExprTree.is(Kind.NOT_EQUAL_TO) - || pBinExprTree.is(Kind.GREATER_THAN_OR_EQUAL_TO) - || pBinExprTree.is(Kind.LESS_THAN_OR_EQUAL_TO)) { - if (pBinExprTree.leftOperand().is(Kind.VARIABLE_IDENTIFIER)) { - analyzeVariables((VariableIdentifierTree) pBinExprTree.leftOperand(), pLevel); - } - if (pBinExprTree.rightOperand().is(Kind.VARIABLE_IDENTIFIER)) { - analyzeVariables((VariableIdentifierTree) pBinExprTree.rightOperand(), pLevel); - } - } + private void visitElseNode(ElseClauseTree pElseTree, int pLevel) { + + if (pElseTree == null) { return; } + + // analyze variables and raise error if needed + computeVariables(pElseTree, pLevel); + + // go to next child level + visitNodeContent(pElseTree.statements(), pLevel + 1); } - private void analyzeVariables(VariableIdentifierTree pVarIdTree, int pLevel) { - if (pVarIdTree.variableExpression().is(Kind.VARIABLE_IDENTIFIER)) { - int nbUsed = variablesStruct.incrementVariableUsageForLevel(pVarIdTree.text(), pLevel); + private void computeVariables(ElseClauseTree pElseTree, int pLevel) { + + for (Map.Entry entry : variablesStruct.getVariables(pLevel).entrySet()) { + String variableName = entry.getKey(); + + // increment usage of all varibales in the same level of ELSE staetement + int nbUsed = variablesStruct.incrementVariableUsageForLevel(variableName, pLevel); // raise an error if maximum if (nbUsed > 2) { - context().newIssue(this, pVarIdTree, ERROR_MESSAGE); + context().newIssue(this, pElseTree, ERROR_MESSAGE); } } } From 0caba6a83830e1cc5199bfc507a9a875625077de Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 25 Jul 2023 12:28:20 +0700 Subject: [PATCH 130/170] [ISSUE 121] refactoring use case multiple-if-else : optimization + correction + refactoring --- .../AvoidMultipleIfElseStatementCheck.java | 169 +++----- .../checks/AvoidMultipleIfElseStatement.php | 396 +++++++++++------- 2 files changed, 322 insertions(+), 243 deletions(-) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java index 7817d4069..d109f8372 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -60,6 +60,8 @@ public class AvoidMultipleIfElseStatementCheck extends PHPSubscriptionCheck { private static VariablesPerLevelDataStructure variablesStruct = new VariablesPerLevelDataStructure(); + // only visit each method to keep data of all conditional tree + // with IF, ELSE or ELSEID statements, we can't keep all data of conditionzl tree @Override public List nodesToVisit() { return List.of(Kind.METHOD_DECLARATION); @@ -103,8 +105,16 @@ private void visitIfNode(IfStatementTree pIfTree, int pLevel) { if (pIfTree == null) return; + // init current if structure with cleaning child levels + variablesStruct.reinitVariableUsageForLevel(pLevel + 1); + // init current if structure with cleaning for else verification + variablesStruct.reinitVariableUsageForLevelForCurrentIfStruct(pLevel); + // analyze condition variables and raise error if needed - computeConditionVariables(pIfTree, pLevel); + computeIfVariables(pIfTree, pLevel); + + // visit the content of if block + visitNodeContent(pIfTree.statements(), pLevel + 1); // analyze ELSEIF clauses if (pIfTree.elseifClauses() != null && !pIfTree.elseifClauses().isEmpty()) { @@ -116,11 +126,9 @@ private void visitIfNode(IfStatementTree pIfTree, int pLevel) { // analyze ELSE clause visitElseNode(pIfTree.elseClause(), pLevel); - // go to next child level of if statement - visitNodeContent(pIfTree.statements(), pLevel + 1); } - private void computeConditionVariables(IfStatementTree pIfTree, int pLevel) { + private void computeIfVariables(IfStatementTree pIfTree, int pLevel) { if (pIfTree.condition() == null) return; @@ -154,8 +162,12 @@ private void computeConditionVariables(BinaryExpressionTree pBinExprTree, int pL private void computeVariables(VariableIdentifierTree pVarIdTree, int pLevel) { if (pVarIdTree.variableExpression().is(Kind.VARIABLE_IDENTIFIER)) { + // add 1 variable count to list of all variables int nbUsed = variablesStruct.incrementVariableUsageForLevel(pVarIdTree.text(), pLevel); + // add 1 variable count to list of variables already declared for current if or elseif struture + variablesStruct.incrementVariableUsageForLevelForCurrentIfStruct(pVarIdTree.text(), pLevel); + // raise an error if maximum if (nbUsed > 2) { context().newIssue(this, pVarIdTree, ERROR_MESSAGE); @@ -167,14 +179,19 @@ private void visitElseIfNode(ElseifClauseTree pElseIfTree, int pLevel) { if (pElseIfTree == null) { return; } + // init current if structure with cleaning child levels + variablesStruct.reinitVariableUsageForLevel(pLevel + 1); + // init current if structure with cleaning for else verification + variablesStruct.reinitVariableUsageForLevelForCurrentIfStruct(pLevel); + // analyze variables and raise error if needed - computeConditionVariables(pElseIfTree, pLevel); + computeElseIfVariables(pElseIfTree, pLevel); // go to next child level visitNodeContent(pElseIfTree.statements(), pLevel + 1); } - private void computeConditionVariables(ElseifClauseTree pElseIfTree, int pLevel) { + private void computeElseIfVariables(ElseifClauseTree pElseIfTree, int pLevel) { if (pElseIfTree.condition() == null) return; @@ -190,20 +207,22 @@ private void visitElseNode(ElseClauseTree pElseTree, int pLevel) { if (pElseTree == null) { return; } // analyze variables and raise error if needed - computeVariables(pElseTree, pLevel); + computeElseVariables(pElseTree, pLevel); // go to next child level visitNodeContent(pElseTree.statements(), pLevel + 1); } - private void computeVariables(ElseClauseTree pElseTree, int pLevel) { + private void computeElseVariables(ElseClauseTree pElseTree, int pLevel) { - for (Map.Entry entry : variablesStruct.getVariables(pLevel).entrySet()) { + for (Map.Entry entry : variablesStruct.getVariablesForCurrentIfStruct(pLevel).entrySet()) { String variableName = entry.getKey(); - // increment usage of all varibales in the same level of ELSE staetement + // increment usage of all variables in the same level of ELSE staetement int nbUsed = variablesStruct.incrementVariableUsageForLevel(variableName, pLevel); + variablesStruct.incrementVariableUsageForLevelForCurrentIfStruct(variableName, pLevel); + // raise an error if maximum if (nbUsed > 2) { context().newIssue(this, pElseTree, ERROR_MESSAGE); @@ -211,53 +230,6 @@ private void computeVariables(ElseClauseTree pElseTree, int pLevel) { } } -// private void checkIfStatementAtTheSameLevel(Tree tree) { -// int countIfStatement = 0; -// -// Tree parentNode = tree.getParent(); -// if (!(parentNode instanceof BlockTree)) { -// return; -// } -// -// // getting parent bloc to count if several IF at the same level -// BlockTree node = (BlockTree) parentNode; -// int sizeBody = node.statements().size(); -// for (int i = 0; i < sizeBody; ++i) { -// if (node.statements().get(i) instanceof IfStatementTree) { -// ++countIfStatement; -// } -// } -// if (countIfStatement > 1) { -// context().newIssue(this, tree, ERROR_MESSAGE); -// } -// } -// -// private void checkElseIfStatement(Tree tree) { -// String ifTree = tree.toString(); -// String findStr = "elseif"; -// int count = countMatches(ifTree, findStr); -// if (count >= 2) { -// context().newIssue(this, tree, ERROR_MESSAGE); -// } -// } -// -// public static int countMatches(String str, String sub) { -// if (isBlankString(str) || isBlankString(sub)) { -// return 0; -// } -// int count = 0; -// int idx = 0; -// while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) { -// count++; -// idx += sub.length(); -// } -// return count; -// } -// -// public static boolean isBlankString(String str) { -// return str == null || str.isBlank(); -// } - /** * Complex data structure representing variables count per AST level (cumulative count with parent levels) * Map> ==> @@ -271,27 +243,34 @@ private static class VariablesPerLevelDataStructure { private final Map> mapVariablesPerLevel; + private final Map> mapVariablesPerLevelForCurrentIfStruct; + public VariablesPerLevelDataStructure() { mapVariablesPerLevel = new HashMap<>(10); + mapVariablesPerLevelForCurrentIfStruct = new HashMap<>(10); } - public VariablesPerLevelDataStructure(Map> pParentLevelMap) { - mapVariablesPerLevel = Map.copyOf(pParentLevelMap); + public Map getVariables(int pLevel) { + return mapVariablesPerLevel.get(pLevel); } public int incrementVariableUsageForLevel(String variableName, int pLevel) { + return internalIncrementVariableUsage(mapVariablesPerLevel, variableName, pLevel); + } + + private int internalIncrementVariableUsage(Map> pDataMap, String variableName, int pLevel) { // get variable usage map for current level - Map variablesMap = mapVariablesPerLevel.get(pLevel); + Map variablesMap = pDataMap.get(pLevel); if (variablesMap == null) { variablesMap = new HashMap<>(5); - mapVariablesPerLevel.put(pLevel, variablesMap); + pDataMap.put(pLevel, variablesMap); } // get usage from parent if needed Integer nbUsed = variablesMap.get(variableName); if (nbUsed == null) { - Integer nbParentUsed = getVariableUsageOfNearestParent(variableName, pLevel - 1); + Integer nbParentUsed = internalGetVariableUsageOfNearestParent(pDataMap, variableName, pLevel - 1); nbUsed = nbParentUsed == null ? 0 : nbParentUsed; } @@ -302,57 +281,43 @@ public int incrementVariableUsageForLevel(String variableName, int pLevel) { return nbUsed; } - private Integer getVariableUsageOfNearestParent(String variableName, int pLevel) { + private Integer internalGetVariableUsageOfNearestParent(Map> pDataMap, String variableName, int pLevel) { Integer nbParentUsed = null; for (int i = pLevel; i >= 0 && nbParentUsed == null; i--) { - Map variablesParentLevelMap = mapVariablesPerLevel.get(i); + Map variablesParentLevelMap = pDataMap.get(i); nbParentUsed = variablesParentLevelMap.get(variableName); } return nbParentUsed; } - public Map getVariables(int pLevel) { - return mapVariablesPerLevel.get(pLevel); + public void reinitVariableUsageForLevel(int pLevel) { + internalReinitVariableUsageForLevelForCurrentIfStruct(mapVariablesPerLevel, pLevel); + } + + private void internalReinitVariableUsageForLevelForCurrentIfStruct(Map> pDataMap, int pLevel) { + if (pDataMap.get(pLevel) == null) { return; } + + // cleaning of current If Structure beginning at level specified + for (int i = pLevel; i < pDataMap.size(); i++) { + pDataMap.remove(i); + } + + } + + public void reinitVariableUsageForLevelForCurrentIfStruct(int pLevel) { + internalReinitVariableUsageForLevelForCurrentIfStruct(mapVariablesPerLevelForCurrentIfStruct, pLevel); + } + + public int incrementVariableUsageForLevelForCurrentIfStruct(String variableName, int pLevel) { + return internalIncrementVariableUsage(mapVariablesPerLevelForCurrentIfStruct, variableName, pLevel); + } + + public Map getVariablesForCurrentIfStruct(int pLevel) { + return mapVariablesPerLevelForCurrentIfStruct.get(pLevel); } -// private Map initializeAndOrGetVariablesMap(int pLevel) { -// -// Map variablesMap = mapVariablesPerLevel.get(pLevel); -// if (variablesMap == null) { -// // getting variables map from parent level to copy to current level if initialization needed -// Map variablesParentLevelMap = mapVariablesPerLevel.get(pLevel - 1); -// } -// -// -// // getting variables map from parent level to copy to current level if initialization needed -// Map variablesParentLevelMap = mapVariablesPerLevel.get(pLevel - 1); -// -// Map variablesMap = mapVariablesPerLevel.computeIfAbsent(pLevel, k -> new HashMap<>(5)); -// -// // variables map initialization : create empty HashMap if needed -// if (variablesParentLevelMap != null && !variablesParentLevelMap.isEmpty() && !variablesMap.isEmpty()) { -// for (Map.Entry entry : variablesParentLevelMap.entrySet()) { -// variablesMap.putIfAbsent(entry.getKey(), entry.getValue()); -// } -// } -// -// return variablesMap; -// } -// -// private void incrementVariableUsageForExistingChildLevels(String variableName, int level) { -// -// // variables map initilization if absent -// Map mapVariables = mapVariablesPerLevel.computeIfAbsent(level, k -> new HashMap<>(5)); -// -// Integer nbUsed = mapVariables.get(variableName); -// if (nbUsed == null) { -// nbUsed = 0; -// } -// nbUsed++; -// mapVariables.put(variableName, nbUsed); -// } } } diff --git a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php index 7c18815f7..3b3fd1047 100644 --- a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php +++ b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php @@ -36,146 +36,162 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa return $nb1; } -// // COMPLIANT -// // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements -// // at the same level AND no problem with several IF staments at the same level using different variables -// public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsedAtDifferentLevels() -// { -// $nb1 = 0; -// $nb2 = 0; -// $nb3 = 0; -// -// if ($nb1 == 1) { -// if ($nb2 == 2) { -// $nb1 = 3; -// } else { -// $nb1 = 4; -// } -// } else { -// $nb2 = 2; -// } -// -// if ($nb3 == 1) { -// if ($nb2 == 2) { -// $nb1 = 3; -// } else { -// $nb1 = 4; -// } -// } else { -// $nb2 = 2; -// } -// -// return $nb1; -// } - -// // COMPLIANT -// // USE CASE : compliant use case to check if one variable is used maximum twice in different IF statements -// public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInIfStatements() -// { -// $nb1 = 0; -// $nb2 = 0; -// -// if ($nb1 == 1) { -// $nb1 = 1; -// } -// -// if ($nb1 == 2) { -// $nb1 = 3; -// } -// -// return $nb1; -// } -// -// // COMPLIANT -// // USE CASE : compliant use case to check if following is OK : -// // - two uses of the same variable -// // - usage of the same variable on different levels of IF statements -// public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInComposedElseStatements() -// { -// $nb1 = 0; -// $nb2 = 0; -// -// if ($nb1 == 1) { -// $nb2 = 2; -// } else { -// if ($nb1 == 2) { -// $nb1 = 1; -// } -// } -// -// return $nb1; -// } -// -// // COMPLIANT -// // USE CASE : compliant use case to check if following is OK : -// // - two uses of the same variable -// // - usage of the same variable on different levels of IF statements -// public function shouldBeCompliantBecauseSereralVariablesUsedMaximumTwiceInComposedElseStatements() -// { -// $nb1 = 0; -// $nb2 = 0; -// $nb3 = 0; -// -// if ($nb1 == 1) { -// $nb2 = 2; -// } else { -// if ($nb2 == 2) { -// $nb1 = 1; -// } else { -// if ($nb3 == 4) { -// $nb1 = 3; -// } else { -// $nb1 = 6; -// } -// } -// } -// -// return $nb1; -// } -// -// // COMPLIANT -// // USE CASE : compliant use case to check if following is OK : -// // - two uses of the same variable -// // - usage of the same variable on different kind of test statements (IF and ELSEIF) -// public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInIfOrElseIfStatements() // Compliant -// { -// $nb1 = 0; -// $nb2 = 10; -// -// if ($nb1 == 1) { -// $nb2 = 1; -// } elseif ($nb1 == $nb2) { -// $nb2 = 2; -// } -// -// return $nb2; -// } -// -// // COMPLIANT -// // USE CASE : compliant use case to check if following is OK : -// // - two uses of the same variable -// // - usage of the same variable on different kind of test statements (IF and ELSEIF) -// public function shouldBeCompliantBecauseSeveralVariablesUsedMaximumTwiceInIfOrElseIfStatements() // Compliant -// { -// $nb1 = 0; -// $nb2 = 10; -// $nb3 = 3; -// $nb4 = 1; -// $nb5 = 2; -// -// if ($nb1 == 1) { -// $nb2 = 1; -// } elseif ($nb3 == $nb2) { -// $nb2 = 2; -// } elseif ($nb4 == $nb5) { -// $nb2 = 4; -// } else { -// $nb2 = 3; -// } -// -// return $nb2; -// } -// + // COMPLIANT + // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements + // at the same level AND no problem with several IF staments at the same level using different variables + public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsedAtDifferentLevels() + { + $nb1 = 0; + $nb2 = 0; + $nb3 = 0; + + if ($nb1 == 1) { + if ($nb2 == 2) { + $nb1 = 3; + } else { + $nb1 = 4; + } + } else { + $nb2 = 2; + } + + if ($nb3 == 1) { + if ($nb2 == 2) { + $nb1 = 3; + } else { + $nb1 = 4; + } + } else { + $nb2 = 2; + } + + return $nb1; + } + + // COMPLIANT + // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements + // at the same level AND no problem with several IF staments at the same level using different variables + public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsedAtDifferentLevelsScenario2() + { + $nb1 = 0; + $nb2 = 0; + $nb3 = 0; + + if ($nb1 == 1) { + if ($nb2 == 2) { + if ($nb3 == 2) { + $nb1 = 3; + } else { + $nb1 = 4; + } + } else { + $nb1 = 4; + } + } else { + $nb2 = 2; + } + + if ($nb3 == 1) { + if ($nb2 == 2) { + $nb1 = 3; + } else { + $nb1 = 4; + } + } else { + $nb2 = 2; + } + + return $nb1; + } + + // COMPLIANT + // USE CASE : compliant use case to check if one variable is used maximum twice in different IF statements + public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInIfStatements() + { + $nb1 = 0; + $nb2 = 0; + + if ($nb1 == 1) { + $nb1 = 1; + } + + if ($nb1 == 2) { + $nb1 = 3; + } + + return $nb1; + } + + // COMPLIANT + // USE CASE : compliant use case to check if following is OK : + // - two uses of the same variable + // - usage of the same variable on different levels of IF statements + public function shouldBeCompliantBecauseSereralVariablesUsedMaximumTwiceInComposedElseStatements() + { + $nb1 = 0; + $nb2 = 0; + $nb3 = 0; + + if ($nb1 == 1) { + $nb2 = 2; + } else { + if ($nb2 == 2) { + $nb1 = 1; + } else { + if ($nb3 == 4) { + $nb1 = 3; + } else { + $nb1 = 6; + } + } + } + + return $nb1; + } + + // COMPLIANT + // USE CASE : compliant use case to check if following is OK : + // - two uses of the same variable + // - usage of the same variable on different kind of test statements (IF and ELSEIF) + public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInIfOrElseIfStatements() // Compliant + { + $nb1 = 0; + $nb2 = 10; + + if ($nb1 == 1) { + $nb2 = 1; + } elseif ($nb1 == $nb2) { + $nb2 = 2; + } + + return $nb2; + } + + // COMPLIANT + // USE CASE : compliant use case to check if following is OK : + // - two uses of the same variable + // - usage of the same variable on different kind of test statements (IF and ELSEIF) + public function shouldBeCompliantBecauseSeveralVariablesUsedMaximumTwiceInIfOrElseIfStatements() // Compliant + { + $nb1 = 0; + $nb2 = 10; + $nb3 = 3; + $nb4 = 1; + $nb5 = 2; + + if ($nb1 == 1) { + $nb2 = 1; + } elseif ($nb3 == $nb2) { + $nb2 = 2; + } elseif ($nb4 == $nb5) { + $nb2 = 4; + } else { + $nb2 = 3; + } + + return $nb2; + } + // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // @@ -184,6 +200,26 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // NON COMPLIANT + // USE CASE : Non compliant use case to check if following is NON OK : + // - two uses of the same variable + // - usage of the same variable on different levels of IF statements + public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInComposedElseStatements() + { + $nb1 = 0; + $nb2 = 0; + + if ($nb1 == 1) { + $nb2 = 2; + } else { + if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb1 = 1; + } + } + + return $nb1; + } + // NON COMPLIANT // USE CASE : NON compliant use case to check if following is NOT COMPLIANT : // one variable is used maximum in two IF / ELSE / ELSEIF statements @@ -214,7 +250,7 @@ public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInIfStatemen $nb2 = 0; if ($nb1 == 1) { - if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} + if ($nb1 == 2) { $nb1 = 1; } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} $nb2 = 3; @@ -248,6 +284,84 @@ public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedEl return $nb1; } + // NON COMPLIANT + // USE CASE : non compliant use case to check if following is NOT OK : + // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE + // - usage of the same variable on different levels of IF statements + public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatementsScenario2() + { + $nb1 = 0; + $nb2 = 0; + + if ($nb1 == 1) { + if ($nb1 == 3) { + $nb1 = 4; + } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb2 = 5; + } + } else { + if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb1 = 1; + } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb2 = 3; + } + } + + return $nb1; + } + + // NON COMPLIANT + // USE CASE : non compliant use case to check if following is NOT OK : + // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE + // - usage of the same variable on different levels of IF statements + public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatementsScenario3() + { + $nb1 = 0; + $nb2 = 0; + + if ($nb1 == 1) { + if ($nb1 == 3) { + $nb1 = 4; + } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb2 = 5; + } + } elseif ($nb2 == 2) { + if ($nb1 == 3) { + $nb1 = 4; + } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb2 = 5; + } + } + + return $nb1; + } + + // NON COMPLIANT + // USE CASE : non compliant use case to check if following is NOT OK : + // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE + // - usage of the same variable on different levels of IF statements + public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatementsScenario4() + { + $nb1 = 0; + $nb2 = 0; + + if ($nb1 == 1) { + if ($nb2 == 3) { + $nb1 = 4; + } else { + $nb1 = 5; + } + } elseif ($nb2 == 2) { + if ($nb1 == 3) { + $nb1 = 4; + } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} + $nb2 = 5; + } + } + + return $nb1; + } + // NON COMPLIANT // USE CASE : NON compliant use case to check if following is NOT OK : // - the same variable must used maximum twice From 0d256a9c643c73c61a84aa879fbde8dfd03e03cd Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Wed, 26 Jul 2023 15:17:32 +0700 Subject: [PATCH 131/170] [ISSUE 121] refactoring use case multiple-if-else : cleaning + adding use cases + small corrections --- .../AvoidMultipleIfElseStatementCheck.java | 27 ++--- ...dMultipleIfElseStatementCheck__BACKUP.java | 103 ------------------ .../l10n/php/rules/custom/EC2.html | 20 +--- .../checks/AvoidMultipleIfElseStatement.php | 24 ++++ 4 files changed, 38 insertions(+), 136 deletions(-) delete mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck__BACKUP.java diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java index d109f8372..0413a8ec0 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -38,11 +38,12 @@ /** * functional description : please see HTML description file of this rule (resources directory) - * technical choices : + * Technical choices : * - Kind.IF_STATEMENT, Kind.ELSE_STATEMENT, Kind.ELSEIF_STATEMENT not used because it isn't possible * to keep parent references to check later if variables already used or not in parent tree * - only one way to keep parent history : manually go throw the all tree and thus, start at method declaration - * - an "ELSE" statement is considered as a second IF statement using the same variables tests + * - an "ELSE" statement is considered as a second IF statement using the same variables used on previous + * IF and ELSEIF statements * */ @Rule( @@ -58,7 +59,7 @@ public class AvoidMultipleIfElseStatementCheck extends PHPSubscriptionCheck { private static final Logger LOGGER = Loggers.get(AvoidMultipleIfElseStatementCheck.class); - private static VariablesPerLevelDataStructure variablesStruct = new VariablesPerLevelDataStructure(); + private VariablesPerLevelDataStructure variablesStruct = new VariablesPerLevelDataStructure(); // only visit each method to keep data of all conditional tree // with IF, ELSE or ELSEID statements, we can't keep all data of conditionzl tree @@ -68,7 +69,7 @@ public List nodesToVisit() { } @Override - public void visitNode(Tree tree) { + public void visitNode(@SuppressWarnings("NullableProblems") Tree tree) { MethodDeclarationTree method = (MethodDeclarationTree)tree; @@ -236,7 +237,7 @@ private void computeElseVariables(ElseClauseTree pElseTree, int pLevel) { * - Key : index of Level (0 = first level) * - Value : Map * - Key : name of variable in the current or parent level - * - Value : number of usage of this variable in a IF statement in current level or one of parent levels + * - Value : number of usage of this variable in an IF statement in current level or one of parent levels * */ private static class VariablesPerLevelDataStructure { @@ -250,22 +251,14 @@ public VariablesPerLevelDataStructure() { mapVariablesPerLevelForCurrentIfStruct = new HashMap<>(10); } - public Map getVariables(int pLevel) { - return mapVariablesPerLevel.get(pLevel); - } - public int incrementVariableUsageForLevel(String variableName, int pLevel) { return internalIncrementVariableUsage(mapVariablesPerLevel, variableName, pLevel); } private int internalIncrementVariableUsage(Map> pDataMap, String variableName, int pLevel) { - // get variable usage map for current level - Map variablesMap = pDataMap.get(pLevel); - if (variablesMap == null) { - variablesMap = new HashMap<>(5); - pDataMap.put(pLevel, variablesMap); - } + // get variable usage map for current level and init if null + Map variablesMap = pDataMap.computeIfAbsent(pLevel, k -> new HashMap<>(5)); // get usage from parent if needed Integer nbUsed = variablesMap.get(variableName); @@ -310,8 +303,8 @@ public void reinitVariableUsageForLevelForCurrentIfStruct(int pLevel) { internalReinitVariableUsageForLevelForCurrentIfStruct(mapVariablesPerLevelForCurrentIfStruct, pLevel); } - public int incrementVariableUsageForLevelForCurrentIfStruct(String variableName, int pLevel) { - return internalIncrementVariableUsage(mapVariablesPerLevelForCurrentIfStruct, variableName, pLevel); + public void incrementVariableUsageForLevelForCurrentIfStruct(String variableName, int pLevel) { + internalIncrementVariableUsage(mapVariablesPerLevelForCurrentIfStruct, variableName, pLevel); } public Map getVariablesForCurrentIfStruct(int pLevel) { diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck__BACKUP.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck__BACKUP.java deleted file mode 100644 index 631781924..000000000 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck__BACKUP.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * SonarQube PHP Custom Rules Example - * Copyright (C) 2016-2016 SonarSource SA - * mailto:contact AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package fr.greencodeinitiative.php.checks; - -import org.sonar.check.Priority; -import org.sonar.check.Rule; -import org.sonar.plugins.php.api.tree.Tree; -import org.sonar.plugins.php.api.tree.Tree.Kind; -import org.sonar.plugins.php.api.tree.statement.BlockTree; -import org.sonar.plugins.php.api.tree.statement.IfStatementTree; -import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; - -import java.util.List; - -@Rule( - key = AvoidMultipleIfElseStatementCheck__BACKUP.RULE_KEY, - name = AvoidMultipleIfElseStatementCheck__BACKUP.ERROR_MESSAGE, - description = AvoidMultipleIfElseStatementCheck__BACKUP.ERROR_MESSAGE, - priority = Priority.MINOR, - tags = {"eco-design", "ecocode", "performance"}) -public class AvoidMultipleIfElseStatementCheck__BACKUP extends PHPSubscriptionCheck { - - public static final String RULE_KEY = "EC2"; - public static final String ERROR_MESSAGE = "Use a switch statement instead of multiple if-else if possible"; - public static final int INDEX_NOT_FOUND = -1; - - @Override - public List nodesToVisit() { - return List.of(Kind.IF_STATEMENT); -// return List.of(Kind.IF_STATEMENT, Kind.ELSEIF_CLAUSE); - } - - @Override - public void visitNode(Tree tree) { - checkIfStatementAtTheSameLevel(tree); - checkElseIfStatement(tree); - } - - private void checkIfStatementAtTheSameLevel(Tree tree) { - int countIfStatement = 0; - - Tree parentNode = tree.getParent(); - if (!(parentNode instanceof BlockTree)) { - return; - } - - // getting parent bloc to count if several IF at the same level - BlockTree node = (BlockTree) parentNode; - int sizeBody = node.statements().size(); - for(int i=0; i 1){ - context().newIssue(this, tree, ERROR_MESSAGE); - } - } - - private void checkElseIfStatement(Tree tree) { - String ifTree = tree.toString(); - String findStr = "elseif"; - int count = countMatches(ifTree, findStr); - if (count >= 2) { - context().newIssue(this, tree, ERROR_MESSAGE); - } - } - - public static int countMatches(String str, String sub) { - if (isBlankString(str) || isBlankString(sub)) { - return 0; - } - int count = 0; - int idx = 0; - while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) { - count++; - idx += sub.length(); - } - return count; - } - - public static boolean isBlankString(String str) { - return str == null || str.length() == 0 || str.isBlank(); - } - -} diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html index a31225e3e..3cfa7e256 100644 --- a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html +++ b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html @@ -1,16 +1,16 @@

      If we are using too many conditional IF, ELSEIF or ELSE statements it will impact performance. We can think of using a switch statement instead of multiple if-else if possible, or refactor code - to reduce number of IF, ELSEIF and ELSE statements. + to reduce number of IF, ELSEIF and ELSE statements. Sometimes called "complexity cyclomatic". Switch statement has a performance advantage over if – else.

      Functional rules : - one variable must be used maximum twice in IF / ELSEIF / ELSE statements at the same level - WARNINGs : - IF and ELSEIF statements use explicitly variable names ! - - ELSE statements sue implicity variabel names ! + - ELSE statements use implicity variable names ! - one variable must be used maximum twice in IF / ELSEIF / ELSE statements at differents hierarchical levels - - we can assume that if one variable is used three times or more (like explain previously), we should : + - we can assume that if one variable is used three times or more, we should : - use a SWITCH statement instead - or refactor the code if possible

      @@ -35,20 +35,8 @@

      Non-compliant Code Example

      $nb = -1; }
      -

      Compliant Code Example : refactor solution

      -
      -    $index = 1;
      -    $nb = 2;
      -    ...
      -    if ($nb == 0 || $nb == 1 || $nb == 2) {
      -        $nb = $index * ($nb + 1);
      -    } else {
      -        $nb = -1;
      -    }
      -    return $nb;
      -
      -

      Compliant Code Example : SWITCH statement solution

      +

      Compliant Code Example : SWITCH statement solution + refactor solution

           $index = 1;
           $nb = 2;
      diff --git a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php
      index 3b3fd1047..8d83f59be 100644
      --- a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php
      +++ b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php
      @@ -220,6 +220,30 @@ public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInComposedElseSt
               return $nb1;
           }
       
      +    // NON COMPLIANT
      +    // USE CASE : non compliant use case to check if a variable is not used maximum twice on several IF / ELSE statements
      +    // at the same level
      +    public function shouldBeNotCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsed()
      +    {
      +        $nb1 = 0;
      +        $nb2 = 0;
      +        $nb3 = 0;
      +
      +        if ($nb3 == 1 && $nb3 == 2 && $nb3 == 3) { // NOK {{Use a switch statement instead of multiple if-else if possible}}
      +            $nb1 = 1;
      +        } else { // NOK {{Use a switch statement instead of multiple if-else if possible}}
      +            $nb2 = 2;
      +        }
      +
      +        if ($nb2 == 2) {
      +            $nb1 = 3;
      +        } else {
      +            $nb1 = 4;
      +        }
      +
      +        return $nb1;
      +    }
      +
           // NON COMPLIANT
           // USE CASE : NON compliant use case to check if following is NOT COMPLIANT :
           // one variable is used maximum in two IF / ELSE / ELSEIF statements
      
      From 07ff46c24c3df78d3e99536ec45c474fc005acb5 Mon Sep 17 00:00:00 2001
      From: David DE CARVALHO 
      Date: Sat, 29 Jul 2023 18:16:47 +0700
      Subject: [PATCH 132/170] [ISSUE 121] refactoring use case multiple-if-else :
       correction JAVA + correction PHP unit
      
      ---
       .../java/checks/AvoidMultipleIfElseStatement.java              | 3 ---
       .../java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java | 2 +-
       2 files changed, 1 insertion(+), 4 deletions(-)
      
      diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java
      index d66fd4583..9460642ab 100644
      --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java
      +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java
      @@ -12,9 +12,6 @@
       import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey;
       
       @Rule(key = "EC2")
      - * functional RULES : please see HTML description file of this rule (resources directory)
      - */
      -
       @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "AMIES")
       public class AvoidMultipleIfElseStatement extends IssuableSubscriptionVisitor {
           protected static final String RULE_MESSAGE = "Using a switch statement instead of multiple if-else if possible";
      diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java
      index 32495c4e1..e64c7e593 100644
      --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java
      +++ b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java
      @@ -77,7 +77,7 @@ void testMetadata() {
       
         @Test
         void testRegistredRules() {
      -    assertThat(repository.rules()).hasSize(9);
      +    assertThat(repository.rules()).hasSize(10);
         }
       
         @Test
      
      From 19907d38d4cfc7510ab519d7ac32d9afb9dc95e3 Mon Sep 17 00:00:00 2001
      From: David DE CARVALHO 
      Date: Sat, 29 Jul 2023 18:30:54 +0700
      Subject: [PATCH 133/170] =?UTF-8?q?[ISSUE=20121]=20refactoring=20use=20cas?=
       =?UTF-8?q?e=20multiple-if-else=20:=20transfo=20fichier=20descr=20r=C3=A8g?=
       =?UTF-8?q?le=20HTML=20en=20asciidoc=20(dans=20nouveau=20projet)?=
      MIME-Version: 1.0
      Content-Type: text/plain; charset=UTF-8
      Content-Transfer-Encoding: 8bit
      
      ---
       .../src/main/rules/EC2/php/EC2.asciidoc       | 54 +++++++++++++++++++
       .../l10n/php/rules/custom/EC2.html            | 54 -------------------
       2 files changed, 54 insertions(+), 54 deletions(-)
       create mode 100644 ecocode-rules-specifications/src/main/rules/EC2/php/EC2.asciidoc
       delete mode 100644 php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html
      
      diff --git a/ecocode-rules-specifications/src/main/rules/EC2/php/EC2.asciidoc b/ecocode-rules-specifications/src/main/rules/EC2/php/EC2.asciidoc
      new file mode 100644
      index 000000000..1e90e5bc4
      --- /dev/null
      +++ b/ecocode-rules-specifications/src/main/rules/EC2/php/EC2.asciidoc
      @@ -0,0 +1,54 @@
      +If we are using too many conditional IF, ELSEIF or ELSE statements it will impact performance.
      +We can think of using a switch statement instead of multiple if-else if possible, or refactor code
      +to reduce number of IF, ELSEIF and ELSE statements. Sometimes called "complexity cyclomatic".
      +Switch statement has a performance advantage over if – else.
      +
      +## Functional rules
      +- one variable must be used maximum twice in IF / ELSEIF / ELSE statements at the same level - WARNINGs :
      +- IF and ELSEIF statements use explicitly variable names !
      +- ELSE statements use implicity variable names !
      +- one variable must be used maximum twice in IF / ELSEIF / ELSE statements at differents hierarchical levels
      +- we can assume that if one variable is used three times or more, we should :
      +- use a SWITCH statement instead
      +- or refactor the code if possible
      +
      +## Non-compliant Code Example
      +
      +NON compliant, becasue `$nb` is used 4 times :
      +- 2 explicit times in IF statements
      +- 2 implicit times in ELSE statements
      +
      +```php
      +$index = 1;
      +$nb = 2;
      +...
      +if ($nb == 0) {
      +    $nb = $index;
      +} elseif ($nb == 1) {
      +    $nb = $index * 2;
      +} elseif ($nb == 2) {
      +    $nb = $index * 3;
      +} else {
      +    $nb = -1;
      +}
      +```
      +
      +## Compliant Code Example
      +
      +SWITCH statement solution + refactor solution
      +
      +```php
      +$index = 1;
      +$nb = 2;
      +...
      +switch ($nb) {
      +    case 0:
      +    case 1:
      +    case 2:
      +        $nb = $index * ($nb + 1);
      +        break;
      +    default:
      +        $nb = -1;
      +}
      +return $nb;
      +```
      diff --git a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html b/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html
      deleted file mode 100644
      index 3cfa7e256..000000000
      --- a/php-plugin/src/main/resources/fr/greencodeinitiative/l10n/php/rules/custom/EC2.html
      +++ /dev/null
      @@ -1,54 +0,0 @@
      -

      - If we are using too many conditional IF, ELSEIF or ELSE statements it will impact performance. - We can think of using a switch statement instead of multiple if-else if possible, or refactor code - to reduce number of IF, ELSEIF and ELSE statements. Sometimes called "complexity cyclomatic". - Switch statement has a performance advantage over if – else. -

      -

      - Functional rules : - - one variable must be used maximum twice in IF / ELSEIF / ELSE statements at the same level - WARNINGs : - - IF and ELSEIF statements use explicitly variable names ! - - ELSE statements use implicity variable names ! - - one variable must be used maximum twice in IF / ELSEIF / ELSE statements at differents hierarchical levels - - we can assume that if one variable is used three times or more, we should : - - use a SWITCH statement instead - - or refactor the code if possible -

      - -

      Non-compliant Code Example

      -

      - NON compliant, becasue `$nb` is used 4 times : - - 2 explicit times in IF statements - - 2 implicit times in ELSE statements -

      -
      -    $index = 1;
      -    $nb = 2;
      -    ...
      -    if ($nb == 0) {
      -        $nb = $index;
      -    } elseif ($nb == 1) {
      -        $nb = $index * 2;
      -    } elseif ($nb == 2) {
      -        $nb = $index * 3;
      -    } else {
      -        $nb = -1;
      -    }
      -
      - -

      Compliant Code Example : SWITCH statement solution + refactor solution

      -
      -    $index = 1;
      -    $nb = 2;
      -    ...
      -    switch ($nb) {
      -        case 0:
      -        case 1:
      -        case 2:
      -            $nb = $index * ($nb + 1);
      -            break;
      -        default:
      -            $nb = -1;
      -    }
      -    return $nb;
      -
      \ No newline at end of file From 867e9a98349bf457a1a0b3a6453858226bb02396 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sat, 29 Jul 2023 18:31:55 +0700 Subject: [PATCH 134/170] [ISSUE 121] refactoring use case multiple-if-else : typo CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6917d4b2..51d2d3995 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - [#121](https://github.com/green-code-initiative/ecoCode/issues/121) new PHP rule : Multiple if-else statement + ### Changed ### Deleted From 1c7f92251404d185fb4b6651fa916ad507916590 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sat, 29 Jul 2023 18:33:42 +0700 Subject: [PATCH 135/170] [ISSUE 121] refactoring use case multiple-if-else : typo CHANGELOG.md BIS --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 51d2d3995..bd0ea72d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- [#121](https://github.com/green-code-initiative/ecoCode/issues/121) new PHP rule : Multiple if-else statement +- [#121](https://github.com/green-code-initiative/ecoCode/issues/121) new PHP rule : Multiple if-else statement + refactoring implementation ### Changed From defc0d4547440db26a069ad23afa4074ce044ec6 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sat, 29 Jul 2023 18:37:21 +0700 Subject: [PATCH 136/170] [ISSUE 121] refactoring use case multiple-if-else : best pratice with ecocode-rules-specifications module --- .../php/checks/AvoidMultipleIfElseStatementCheck.java | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java index 0413a8ec0..480a8a7b4 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -21,7 +21,6 @@ import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; -import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.php.api.tree.Tree; import org.sonar.plugins.php.api.tree.Tree.Kind; @@ -46,15 +45,9 @@ * IF and ELSEIF statements * */ -@Rule( - key = AvoidMultipleIfElseStatementCheck.RULE_KEY, - name = AvoidMultipleIfElseStatementCheck.ERROR_MESSAGE, - description = AvoidMultipleIfElseStatementCheck.ERROR_MESSAGE, - priority = Priority.MINOR, - tags = {"eco-design", "ecocode", "performance"}) +@Rule(key = "EC2") public class AvoidMultipleIfElseStatementCheck extends PHPSubscriptionCheck { - public static final String RULE_KEY = "EC2"; public static final String ERROR_MESSAGE = "Use a switch statement instead of multiple if-else if possible"; private static final Logger LOGGER = Loggers.get(AvoidMultipleIfElseStatementCheck.class); From f9ffbc6a437b4975b42e43cadd1a106dcd3f8a11 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sat, 29 Jul 2023 18:38:57 +0700 Subject: [PATCH 137/170] [ISSUE 121] refactoring use case multiple-if-else : update TODOs_DDC.md --- TODOs_DDC.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/TODOs_DDC.md b/TODOs_DDC.md index 20f74d2d9..1cec0dede 100644 --- a/TODOs_DDC.md +++ b/TODOs_DDC.md @@ -11,9 +11,9 @@ actions vues perso : - nettoyer le MIGRATION_TODOs.md - ménage dans les branches de dev (local et remote) - JYC : suppression dépendance analyser-commons ==> check si bien tout nettoyé (version dans pom, référence dans code) -- créer issue sur la rule EC2 sur JAVA : +- créer issue sur la rule EC2 (`avoidMultipleIfElse`) sur JAVA : - à refondre avec les uses cases du PHP + implem du PHP (en cours - PR_160_recup) - JAVA : existe depuis longtemps !!! normal que l'implem PHP et python aient le même code minimaliste fonctionellement -- voir les rules désativées chez PJ, créer des issues et corriger : - - voir si justement s'il n'y a pas la EC2 dans le lot - - voir pourquoi désactivées car ralaient trop \ No newline at end of file +- voir les rules désativées chez PJ, créer des issues et corriger (`avoidMultipleIfElse`) : + - voir pourquoi désactivées car ralaient trop + - retester le EC2 \ No newline at end of file From b6505f79601428c3d87fa70ba8ab6ac46eeaf4f1 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sat, 29 Jul 2023 18:39:44 +0700 Subject: [PATCH 138/170] =?UTF-8?q?[ISSUE=20121]=20refactoring=20use=20cas?= =?UTF-8?q?e=20multiple-if-else=20:=20transfo=20fichier=20descr=20r=C3=A8g?= =?UTF-8?q?le=20HTML=20en=20asciidoc=20(dans=20nouveau=20projet)=20-=20typ?= =?UTF-8?q?o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/rules/EC2/php/EC2.asciidoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ecocode-rules-specifications/src/main/rules/EC2/php/EC2.asciidoc b/ecocode-rules-specifications/src/main/rules/EC2/php/EC2.asciidoc index 1e90e5bc4..2e77a982a 100644 --- a/ecocode-rules-specifications/src/main/rules/EC2/php/EC2.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC2/php/EC2.asciidoc @@ -14,7 +14,7 @@ Switch statement has a performance advantage over if – else. ## Non-compliant Code Example -NON compliant, becasue `$nb` is used 4 times : +NON compliant, because `$nb` is used 4 times : - 2 explicit times in IF statements - 2 implicit times in ELSE statements From 666e79152c92df6a8147e953faf702cbf9e9aed2 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 4 Aug 2023 09:09:44 +0200 Subject: [PATCH 139/170] [ISSUE 121] refactoring use case multiple-if-else : add comment + refacto input param names --- .../AvoidMultipleIfElseStatementCheck.java | 89 +++++++++++++++---- 1 file changed, 70 insertions(+), 19 deletions(-) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java index 480a8a7b4..d9ed31b65 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -36,14 +36,13 @@ import java.util.Map; /** - * functional description : please see HTML description file of this rule (resources directory) - * Technical choices : + * FUNCTIONAL DESCRIPTION : please see ASCIIDOC description file of this rule (inside `ecocode-rules-spcifications`) + * TECHNICAL CHOICES : * - Kind.IF_STATEMENT, Kind.ELSE_STATEMENT, Kind.ELSEIF_STATEMENT not used because it isn't possible * to keep parent references to check later if variables already used or not in parent tree * - only one way to keep parent history : manually go throw the all tree and thus, start at method declaration * - an "ELSE" statement is considered as a second IF statement using the same variables used on previous - * IF and ELSEIF statements - * + * - IF and ELSEIF statements are considered as an IF statement */ @Rule(key = "EC2") public class AvoidMultipleIfElseStatementCheck extends PHPSubscriptionCheck { @@ -52,19 +51,20 @@ public class AvoidMultipleIfElseStatementCheck extends PHPSubscriptionCheck { private static final Logger LOGGER = Loggers.get(AvoidMultipleIfElseStatementCheck.class); + // data structure for following usage of variable inside all the AST tree private VariablesPerLevelDataStructure variablesStruct = new VariablesPerLevelDataStructure(); // only visit each method to keep data of all conditional tree - // with IF, ELSE or ELSEID statements, we can't keep all data of conditionzl tree + // with IF, ELSE or ELSEIF statements, we can't keep all data of conditional tree @Override public List nodesToVisit() { return List.of(Kind.METHOD_DECLARATION); } @Override - public void visitNode(@SuppressWarnings("NullableProblems") Tree tree) { + public void visitNode(@SuppressWarnings("NullableProblems") Tree pTree) { - MethodDeclarationTree method = (MethodDeclarationTree)tree; + MethodDeclarationTree method = (MethodDeclarationTree)pTree; if (!method.body().is(Kind.BLOCK)) { return; @@ -73,35 +73,44 @@ public void visitNode(@SuppressWarnings("NullableProblems") Tree tree) { // reinit data structure before each method analysis variablesStruct = new VariablesPerLevelDataStructure(); + // starting visit visitNodeContent(((BlockTree) method.body()).statements(), 0); } - private void visitNodeContent(List lstStatements, int pLevel) { - if (lstStatements == null || lstStatements.isEmpty()) { + /** + * Visit all content of a node for one level (with its statements list) + * + * @param pLstStatements statements list of current node + * @param pLevel level of current node + */ + private void visitNodeContent(List pLstStatements, int pLevel) { + if (pLstStatements == null || pLstStatements.isEmpty()) { return; } - for (StatementTree statement : lstStatements) { + for (StatementTree statement : pLstStatements) { if (statement.is(Kind.BLOCK)) { - LOGGER.debug("BLOCK node - go to child nodes : {}", statement.toString()); - visitNodeContent(((BlockTree)statement).statements(), pLevel); // Block Statement is not a new LEVEL + // the cirrent node is a block : visit block content + visitNodeContent(((BlockTree)statement).statements(), pLevel); } else if (statement.is(Kind.IF_STATEMENT)) { - LOGGER.debug("Visiting IF_STATEMENT node : {}", statement.toString()); visitIfNode((IfStatementTree)statement, pLevel); - } else { - LOGGER.debug("NO node visit because of incompatibility : {}", statement.toString()); } } } + /** + * Visit an IF type node + * @param pIfTree the current node (Tree type) + * @param pLevel the level of node + */ private void visitIfNode(IfStatementTree pIfTree, int pLevel) { if (pIfTree == null) return; // init current if structure with cleaning child levels variablesStruct.reinitVariableUsageForLevel(pLevel + 1); - // init current if structure with cleaning for else verification + // init current if structure with cleaning for ELSE process checking variablesStruct.reinitVariableUsageForLevelForCurrentIfStruct(pLevel); // analyze condition variables and raise error if needed @@ -122,10 +131,16 @@ private void visitIfNode(IfStatementTree pIfTree, int pLevel) { } + /** + * Analyze and compute variables usage for IF AST structure + * @param pIfTree IF node + * @param pLevel the level of IF node + */ private void computeIfVariables(IfStatementTree pIfTree, int pLevel) { if (pIfTree.condition() == null) return; + // analysing content of conditions of IF node ExpressionTree expr = pIfTree.condition().expression(); if (expr instanceof BinaryExpressionTree) { computeConditionVariables((BinaryExpressionTree) expr, pLevel); @@ -133,7 +148,14 @@ private void computeIfVariables(IfStatementTree pIfTree, int pLevel) { } + /** + * Analyze and compute variables usage for Expression structure + * @param pBinExprTree binary expression to analyze + * @param pLevel The level of binary expression + */ private void computeConditionVariables(BinaryExpressionTree pBinExprTree, int pLevel) { + + // if multiple conditions, continue with each part of complex expression if (pBinExprTree.is(Kind.CONDITIONAL_AND) || pBinExprTree.is(Kind.CONDITIONAL_OR)) { if (pBinExprTree.leftOperand() instanceof BinaryExpressionTree) { computeConditionVariables((BinaryExpressionTree) pBinExprTree.leftOperand(), pLevel); @@ -145,6 +167,7 @@ private void computeConditionVariables(BinaryExpressionTree pBinExprTree, int pL || pBinExprTree.is(Kind.NOT_EQUAL_TO) || pBinExprTree.is(Kind.GREATER_THAN_OR_EQUAL_TO) || pBinExprTree.is(Kind.LESS_THAN_OR_EQUAL_TO)) { + // continue analyze with variables if some key-words are found if (pBinExprTree.leftOperand().is(Kind.VARIABLE_IDENTIFIER)) { computeVariables((VariableIdentifierTree) pBinExprTree.leftOperand(), pLevel); } @@ -154,12 +177,17 @@ private void computeConditionVariables(BinaryExpressionTree pBinExprTree, int pL } } + /** + * Analyze and compute variables usage for Variable AST structure + * @param pVarIdTree The Variable AST structure + * @param pLevel the level of structure + */ private void computeVariables(VariableIdentifierTree pVarIdTree, int pLevel) { if (pVarIdTree.variableExpression().is(Kind.VARIABLE_IDENTIFIER)) { - // add 1 variable count to list of all variables + // increment the variable counter to list of all variables int nbUsed = variablesStruct.incrementVariableUsageForLevel(pVarIdTree.text(), pLevel); - // add 1 variable count to list of variables already declared for current if or elseif struture + // increment variable counter to list of variables already declared for current if or elseif struture variablesStruct.incrementVariableUsageForLevelForCurrentIfStruct(pVarIdTree.text(), pLevel); // raise an error if maximum @@ -169,12 +197,18 @@ private void computeVariables(VariableIdentifierTree pVarIdTree, int pLevel) { } } + /** + * Analyze and compute variables usage for ELSEIF AST structure + * @param pElseIfTree ELSEIF node + * @param pLevel the level of ELSEIF node + */ private void visitElseIfNode(ElseifClauseTree pElseIfTree, int pLevel) { if (pElseIfTree == null) { return; } // init current if structure with cleaning child levels variablesStruct.reinitVariableUsageForLevel(pLevel + 1); + // init current if structure with cleaning for else verification variablesStruct.reinitVariableUsageForLevelForCurrentIfStruct(pLevel); @@ -185,6 +219,11 @@ private void visitElseIfNode(ElseifClauseTree pElseIfTree, int pLevel) { visitNodeContent(pElseIfTree.statements(), pLevel + 1); } + /** + * Analyze and compute variables usage for ELSEIF AST structure + * @param pElseIfTree ELSEIF node + * @param pLevel the level of ELSEIF node + */ private void computeElseIfVariables(ElseifClauseTree pElseIfTree, int pLevel) { if (pElseIfTree.condition() == null) return; @@ -196,6 +235,11 @@ private void computeElseIfVariables(ElseifClauseTree pElseIfTree, int pLevel) { } + /** + * Analyze and compute variables usage for ELSE AST structure + * @param pElseTree ELSE node + * @param pLevel the level of ELSE node + */ private void visitElseNode(ElseClauseTree pElseTree, int pLevel) { if (pElseTree == null) { return; } @@ -207,6 +251,11 @@ private void visitElseNode(ElseClauseTree pElseTree, int pLevel) { visitNodeContent(pElseTree.statements(), pLevel + 1); } + /** + * Analyze and compute variables usage for ELSE AST structure + * @param pElseTree ELSE node + * @param pLevel the level of ELSE node + */ private void computeElseVariables(ElseClauseTree pElseTree, int pLevel) { for (Map.Entry entry : variablesStruct.getVariablesForCurrentIfStruct(pLevel).entrySet()) { @@ -215,6 +264,7 @@ private void computeElseVariables(ElseClauseTree pElseTree, int pLevel) { // increment usage of all variables in the same level of ELSE staetement int nbUsed = variablesStruct.incrementVariableUsageForLevel(variableName, pLevel); + // increment variable counter to list of variables already declared for current if or elseif struture variablesStruct.incrementVariableUsageForLevelForCurrentIfStruct(variableName, pLevel); // raise an error if maximum @@ -225,7 +275,7 @@ private void computeElseVariables(ElseClauseTree pElseTree, int pLevel) { } /** - * Complex data structure representing variables count per AST level (cumulative count with parent levels) + * Complex data structure representing variables counters per AST level (cumulative counts with parent levels) * Map> ==> * - Key : index of Level (0 = first level) * - Value : Map @@ -235,6 +285,7 @@ private void computeElseVariables(ElseClauseTree pElseTree, int pLevel) { */ private static class VariablesPerLevelDataStructure { + private final Map> mapVariablesPerLevel; private final Map> mapVariablesPerLevelForCurrentIfStruct; From dc380121a79274b5836343c80a3055d68b1984e6 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 4 Aug 2023 10:11:28 +0200 Subject: [PATCH 140/170] [ISSUE 121] refactoring use case multiple-if-else : add code comment --- .../AvoidMultipleIfElseStatementCheck.java | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java index d9ed31b65..738b8ddf1 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -285,9 +285,12 @@ private void computeElseVariables(ElseClauseTree pElseTree, int pLevel) { */ private static class VariablesPerLevelDataStructure { - + // global map variable counters per level private final Map> mapVariablesPerLevel; + // map variable counters per level for current If / ElseIf structure + // purpose : used by compute variables Else process (because Else structure is particular : + // we don't know previous variables and we need previous If / ElseIf structure to know variables) private final Map> mapVariablesPerLevelForCurrentIfStruct; public VariablesPerLevelDataStructure() { @@ -295,10 +298,16 @@ public VariablesPerLevelDataStructure() { mapVariablesPerLevelForCurrentIfStruct = new HashMap<>(10); } + /** + * increment variable counters on global map + */ public int incrementVariableUsageForLevel(String variableName, int pLevel) { return internalIncrementVariableUsage(mapVariablesPerLevel, variableName, pLevel); } + /** + * increment variable counters on input map + */ private int internalIncrementVariableUsage(Map> pDataMap, String variableName, int pLevel) { // get variable usage map for current level and init if null @@ -318,6 +327,9 @@ private int internalIncrementVariableUsage(Map> pD return nbUsed; } + /** + * get usage of a variable in top tree (nearest top parent) + */ private Integer internalGetVariableUsageOfNearestParent(Map> pDataMap, String variableName, int pLevel) { Integer nbParentUsed = null; @@ -329,10 +341,16 @@ private Integer internalGetVariableUsageOfNearestParent(Map> pDataMap, int pLevel) { if (pDataMap.get(pLevel) == null) { return; } @@ -343,14 +361,23 @@ private void internalReinitVariableUsageForLevelForCurrentIfStruct(Map getVariablesForCurrentIfStruct(int pLevel) { return mapVariablesPerLevelForCurrentIfStruct.get(pLevel); } From 463afef50dcd2ff0e1c41e690ae7779f59b53295 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 4 Aug 2023 10:31:24 +0200 Subject: [PATCH 141/170] [ISSUE 121] refactoring use case multiple-if-else : cleaning --- .../php/checks/AvoidMultipleIfElseStatementCheck.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java index 738b8ddf1..2526a6085 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -19,8 +19,6 @@ */ package fr.greencodeinitiative.php.checks; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; import org.sonar.check.Rule; import org.sonar.plugins.php.api.tree.Tree; import org.sonar.plugins.php.api.tree.Tree.Kind; @@ -49,8 +47,6 @@ public class AvoidMultipleIfElseStatementCheck extends PHPSubscriptionCheck { public static final String ERROR_MESSAGE = "Use a switch statement instead of multiple if-else if possible"; - private static final Logger LOGGER = Loggers.get(AvoidMultipleIfElseStatementCheck.class); - // data structure for following usage of variable inside all the AST tree private VariablesPerLevelDataStructure variablesStruct = new VariablesPerLevelDataStructure(); From 5e2aa4d13f918a7a57115db0ca776698f1d26690 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 4 Aug 2023 10:45:19 +0200 Subject: [PATCH 142/170] [ISSUE 121] refactoring use case multiple-if-else : optim + TU --- .../php/checks/AvoidMultipleIfElseStatementCheck.java | 5 ++++- .../resources/checks/AvoidMultipleIfElseStatement.php | 8 ++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java index 2526a6085..5661853cb 100644 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java @@ -161,8 +161,11 @@ private void computeConditionVariables(BinaryExpressionTree pBinExprTree, int pL } } else if (pBinExprTree.is(Kind.EQUAL_TO) || pBinExprTree.is(Kind.NOT_EQUAL_TO) + || pBinExprTree.is(Kind.GREATER_THAN) || pBinExprTree.is(Kind.GREATER_THAN_OR_EQUAL_TO) - || pBinExprTree.is(Kind.LESS_THAN_OR_EQUAL_TO)) { + || pBinExprTree.is(Kind.LESS_THAN_OR_EQUAL_TO) + || pBinExprTree.is(Kind.LESS_THAN) + ) { // continue analyze with variables if some key-words are found if (pBinExprTree.leftOperand().is(Kind.VARIABLE_IDENTIFIER)) { computeVariables((VariableIdentifierTree) pBinExprTree.leftOperand(), pLevel); diff --git a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php index 8d83f59be..f1c315eac 100644 --- a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php +++ b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php @@ -21,7 +21,7 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa $nb2 = 0; $nb3 = 0; - if ($nb3 == 1 && $nb1 == 1) { + if ($nb3 != 1 && $nb1 > 1) { $nb1 = 1; } else { $nb2 = 2; @@ -45,7 +45,7 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa $nb2 = 0; $nb3 = 0; - if ($nb1 == 1) { + if ($nb1 < 1) { if ($nb2 == 2) { $nb1 = 3; } else { @@ -55,7 +55,7 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa $nb2 = 2; } - if ($nb3 == 1) { + if ($nb3 >= 1) { if ($nb2 == 2) { $nb1 = 3; } else { @@ -77,7 +77,7 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa $nb2 = 0; $nb3 = 0; - if ($nb1 == 1) { + if ($nb1 <= 1) { if ($nb2 == 2) { if ($nb3 == 2) { $nb1 = 3; From 90667c417bcfec969e1b882f0ac3dd108e214880 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 4 Aug 2023 12:06:23 +0200 Subject: [PATCH 143/170] [ISSUE 121] refactoring use case multiple-if-else : test file - optim --- .../checks/AvoidMultipleIfElseStatement.php | 68 +++++++++---------- 1 file changed, 31 insertions(+), 37 deletions(-) diff --git a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php index f1c315eac..329179478 100644 --- a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php +++ b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php @@ -39,7 +39,7 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa // COMPLIANT // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements // at the same level AND no problem with several IF staments at the same level using different variables - public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsedAtDifferentLevels() + public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsedAtDiffLevels() { $nb1 = 0; $nb2 = 0; @@ -47,9 +47,9 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa if ($nb1 < 1) { if ($nb2 == 2) { - $nb1 = 3; + $nb3 = 3; } else { - $nb1 = 4; + $nb3 = 4; } } else { $nb2 = 2; @@ -62,7 +62,7 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa $nb1 = 4; } } else { - $nb2 = 2; + $nb1 = 2; } return $nb1; @@ -71,7 +71,7 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa // COMPLIANT // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements // at the same level AND no problem with several IF staments at the same level using different variables - public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsedAtDifferentLevelsScenario2() + public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDiffVariablesUsedAtDiffLevelsScenario2() { $nb1 = 0; $nb2 = 0; @@ -80,12 +80,12 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa if ($nb1 <= 1) { if ($nb2 == 2) { if ($nb3 == 2) { - $nb1 = 3; + $nb3 = 3; } else { - $nb1 = 4; + $nb3 = 4; } } else { - $nb1 = 4; + $nb3 = 4; } } else { $nb2 = 2; @@ -98,7 +98,7 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa $nb1 = 4; } } else { - $nb2 = 2; + $nb1 = 2; } return $nb1; @@ -109,7 +109,6 @@ public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVa public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInIfStatements() { $nb1 = 0; - $nb2 = 0; if ($nb1 == 1) { $nb1 = 1; @@ -133,7 +132,7 @@ public function shouldBeCompliantBecauseSereralVariablesUsedMaximumTwiceInCompos $nb3 = 0; if ($nb1 == 1) { - $nb2 = 2; + $nb1 = 2; } else { if ($nb2 == 2) { $nb1 = 1; @@ -207,10 +206,9 @@ public function shouldBeCompliantBecauseSeveralVariablesUsedMaximumTwiceInIfOrEl public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInComposedElseStatements() { $nb1 = 0; - $nb2 = 0; if ($nb1 == 1) { - $nb2 = 2; + $nb1 = 2; } else { if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} $nb1 = 1; @@ -221,7 +219,7 @@ public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInComposedElseSt } // NON COMPLIANT - // USE CASE : non compliant use case to check if a variable is not used maximum twice on several IF / ELSE statements + // USE CASE : non compliant use case to check if a variable is not used max twice on several IF / ELSE statements // at the same level public function shouldBeNotCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsed() { @@ -229,7 +227,9 @@ public function shouldBeNotCompliantBecauseVariablesUsedMaximumTwiceAndDifferent $nb2 = 0; $nb3 = 0; - if ($nb3 == 1 && $nb3 == 2 && $nb3 == 3) { // NOK {{Use a switch statement instead of multiple if-else if possible}} + if ($nb3 == 1 + && $nb3 == 2 + && $nb3 == 3) { // NOK {{Use a switch statement instead of multiple if-else if possible}} $nb1 = 1; } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} $nb2 = 2; @@ -250,16 +250,15 @@ public function shouldBeNotCompliantBecauseVariablesUsedMaximumTwiceAndDifferent public function shouldBeNotCompliantBecauseVariablesIsUsedMoreThanTwice() { $nb1 = 0; - $nb2 = 0; if ($nb1 == 1) { - $nb1 = 1; + $nb1 = 2; } else { - $nb2 = 2; + $nb1 = 3; } if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb2 = 3; + $nb1 = 4; } return $nb1; @@ -271,16 +270,15 @@ public function shouldBeNotCompliantBecauseVariablesIsUsedMoreThanTwice() public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInIfStatementsAtDifferentsLevels() { $nb1 = 0; - $nb2 = 0; if ($nb1 == 1) { if ($nb1 == 2) { $nb1 = 1; } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb2 = 3; + $nb1 = 3; } } else { - $nb2 = 2; + $nb1 = 2; } return $nb1; @@ -293,15 +291,14 @@ public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInIfStatemen public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatements() { $nb1 = 0; - $nb2 = 0; if ($nb1 == 1) { - $nb2 = 2; + $nb1 = 2; } else { if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} $nb1 = 1; } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb2 = 3; + $nb1 = 3; } } @@ -315,19 +312,18 @@ public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedEl public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatementsScenario2() { $nb1 = 0; - $nb2 = 0; if ($nb1 == 1) { if ($nb1 == 3) { $nb1 = 4; } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb2 = 5; + $nb1 = 5; } } else { if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} $nb1 = 1; } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb2 = 3; + $nb1 = 3; } } @@ -347,13 +343,13 @@ public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedEl if ($nb1 == 3) { $nb1 = 4; } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb2 = 5; + $nb1 = 5; } } elseif ($nb2 == 2) { - if ($nb1 == 3) { - $nb1 = 4; + if ($nb1 == 4) { + $nb1 = 5; } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb2 = 5; + $nb1 = 6; } } @@ -379,7 +375,7 @@ public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedEl if ($nb1 == 3) { $nb1 = 4; } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb2 = 5; + $nb1 = 5; } } @@ -393,10 +389,9 @@ public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedEl public function shouldBeNotCompliantBecauseVariableUsedMaximumTwiceInComposedElseStatements() { $nb1 = 0; - $nb2 = 0; if ($nb1 == 1) { - $nb2 = 2; + $nb1 = 2; } else { if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} $nb1 = 1; @@ -404,7 +399,7 @@ public function shouldBeNotCompliantBecauseVariableUsedMaximumTwiceInComposedEls if ($nb1 == 3) { // NOK {{Use a switch statement instead of multiple if-else if possible}} $nb1 = 4; } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb2 = 5; + $nb1 = 5; } } } @@ -420,7 +415,6 @@ public function shouldBeNotCompliantBecauseTheSameVariableIsUsedMoreThanTwice() { $nb1 = 0; $nb2 = 10; - $nb3 = 11; if ($nb1 == 1) { $nb2 = 1; From c5c75895e31d3ed542408b9c749a655e3f1864b8 Mon Sep 17 00:00:00 2001 From: jycr Date: Tue, 11 Jul 2023 10:48:43 +0200 Subject: [PATCH 144/170] Adds missing information for publishing to Maven Central --- .../workflows/publish_to_maven_central.yml | 57 +++++++++ pom.xml | 121 ++++++++++++++++++ 2 files changed, 178 insertions(+) create mode 100644 .github/workflows/publish_to_maven_central.yml diff --git a/.github/workflows/publish_to_maven_central.yml b/.github/workflows/publish_to_maven_central.yml new file mode 100644 index 000000000..cec3daa0b --- /dev/null +++ b/.github/workflows/publish_to_maven_central.yml @@ -0,0 +1,57 @@ +# This workflow will build a Java project with Maven and publish artifact to Maven Central (https://search.maven.org) +# +# After deploy to https://s01.oss.sonatype.org finished, manual steps is required : +# - Go to: https://s01.oss.sonatype.org/#stagingRepositories +# - Check upload and if all is right, "Close" corresponding Staging Repository +# - "Release" corresponding Staging Repository +# - Wait some hours and then check availability of release on Maven central: https://search.maven.org/search?q=g:io.ecocode +# +# Additional information: +# - https://docs.github.com/en/actions/publishing-packages/publishing-java-packages-with-maven#publishing-packages-to-the-maven-central-repository +# - https://blogs.itemis.com/en/github-actions-releasing-artifacts-into-maven-central + +name: Publish package to the Maven Central Repository + +on: + release: + types: [ published ] + +jobs: + publish: + name: Deploy to Maven central + runs-on: ubuntu-latest + + steps: + # Checks out a copy of project's repository. + - name: Checkout + uses: actions/checkout@v3 + + # Sets up the Java JDK, and also configures the Maven `settings.xml` file to add authentication for the + # `ossrh` repository using the `OSSRH_USERNAME` and `OSSRH_TOKEN` environment variables. + - name: Set up Maven Central Repository + uses: actions/setup-java@v3 + with: + java-version: '11' + distribution: 'adopt' + server-id: 'ossrh' # must match the serverId configured for the nexus-staging-maven-plugin in `pom.xml` + server-username: OSSRH_USERNAME + server-password: OSSRH_TOKEN + gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Substituted with the value stored in the referenced secret + gpg-passphrase: MAVEN_GPG_PASSPHRASE # Env var that holds the key's passphrase + + - name: Cache Maven packages + uses: actions/cache@v1 + with: + path: ~/.m2 + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-m2 + + # Runs the Maven command to publish to the `ossrh` repository. + # The `OSSRH_USERNAME` environment variable will be set with the contents of your `OSSRH_USERNAME` secret, + # and the `OSSRH_TOKEN` environment variable will be set with the contents of your `OSSRH_TOKEN` secret. + - name: Publish package + run: mvn --batch-mode deploy -Pmaven-central-publishing + env: + OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} + OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} diff --git a/pom.xml b/pom.xml index a5f7a0c4c..1f7d02e26 100644 --- a/pom.xml +++ b/pom.xml @@ -22,6 +22,61 @@ + + + + Gilles Grousset + zippy1978@users.noreply.github.com + green-code-initiative + https://github.com/green-code-initiative + + + Maxime Malgorn + utarwyn@users.noreply.github.com + green-code-initiative + https://github.com/green-code-initiative + + + Geoffrey Lalloué + glalloue@users.noreply.github.com + green-code-initiative + https://github.com/green-code-initiative + + + David DE CARVALHO + dedece35@users.noreply.github.com + green-code-initiative + https://github.com/green-code-initiative + + + Olivier Le Goaër + olegoaer@users.noreply.github.com + green-code-initiative + https://github.com/green-code-initiative + + + Julien Hertout + jhertout@users.noreply.github.com + green-code-initiative + https://github.com/green-code-initiative + + + Jules Delecour + jules-delecour-dav@users.noreply.github.com + green-code-initiative + https://github.com/green-code-initiative + + + DUBOIS Maxime + mdubois81@users.noreply.github.com + green-code-initiative + https://github.com/green-code-initiative + + + ecocode-rules-specifications python-plugin @@ -236,4 +291,70 @@ + + + + maven-central-publishing + + + + + ossrh + https://s01.oss.sonatype.org/content/repositories/snapshots + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.13 + true + + ossrh + https://s01.oss.sonatype.org/ + true + + + + org.apache.maven.plugins + maven-gpg-plugin + 3.1.0 + + + sign-artifacts + verify + + sign + + + + --pinentry-mode + loopback + + + + + + + + + From cf4784a560fbfa7d78fbb6476bfe96b8890fb0fa Mon Sep 17 00:00:00 2001 From: jycr Date: Tue, 8 Aug 2023 17:24:41 +0200 Subject: [PATCH 145/170] Changes workflow trigger for Maven Central publishing --- .github/workflows/publish_to_maven_central.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/publish_to_maven_central.yml b/.github/workflows/publish_to_maven_central.yml index cec3daa0b..19de389e8 100644 --- a/.github/workflows/publish_to_maven_central.yml +++ b/.github/workflows/publish_to_maven_central.yml @@ -13,8 +13,7 @@ name: Publish package to the Maven Central Repository on: - release: - types: [ published ] + workflow_dispatch: jobs: publish: From 1c117bc2aaf8c5197fe2cd549a4bf87456f0c4a5 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Sat, 5 Aug 2023 23:47:34 +0200 Subject: [PATCH 146/170] [ISSUE 142] new python rule : AvoidMultipleIfElseStatement --- .../src/main/rules/EC2/php/EC2.asciidoc | 1 + .../src/main/rules/EC2/python/EC2.asciidoc | 54 +++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 ecocode-rules-specifications/src/main/rules/EC2/python/EC2.asciidoc diff --git a/ecocode-rules-specifications/src/main/rules/EC2/php/EC2.asciidoc b/ecocode-rules-specifications/src/main/rules/EC2/php/EC2.asciidoc index 2e77a982a..eae2c2817 100644 --- a/ecocode-rules-specifications/src/main/rules/EC2/php/EC2.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC2/php/EC2.asciidoc @@ -31,6 +31,7 @@ if ($nb == 0) { } else { $nb = -1; } +return $nb; ``` ## Compliant Code Example diff --git a/ecocode-rules-specifications/src/main/rules/EC2/python/EC2.asciidoc b/ecocode-rules-specifications/src/main/rules/EC2/python/EC2.asciidoc new file mode 100644 index 000000000..f9de6b834 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC2/python/EC2.asciidoc @@ -0,0 +1,54 @@ +If we are using too many conditional IF, ELSEIF or ELSE statements it will impact performance. +We can think of using a switch statement instead of multiple if-else if possible, or refactor code +to reduce number of IF, ELSEIF and ELSE statements. Sometimes called "complexity cyclomatic". +MATCH-CASE statement has a performance advantage over if – else. + +## Functional rules +- one variable must be used maximum twice in IF / ELSEIF / ELSE statements at the same level - WARNINGs : +- IF and ELSEIF statements use explicitly variable names ! +- ELSE statements use implicity variable names ! +- one variable must be used maximum twice in IF / ELSEIF / ELSE statements at differents hierarchical levels +- we can assume that if one variable is used three times or more, we should : +- use a MATCHS-CASE statement instead +- or refactor the code if possible + +## Non-compliant Code Example + +NON compliant, because `nb` is used 4 times : +- 2 explicit times in IF statements +- 2 implicit times in ELSE statements + +```python +index = 1 +nb = 2 +... +if nb == 0: + nb = index +elif nb == 1: + nb = index * 2 +elif nb == 2: + nb = index * 3 +else: + nb = -1 +return nb +``` + +## Compliant Code Example + +MATCH-CASE statement solution + refactor solution + +```python +index = 1 +nb = 2 +... +match nb: + case 0: + nb = index * (nb + 1) + case 1: + nb = index * (nb + 1) + case 2: + nb = index * (nb + 1) + case _: + nb = -1 +return nb +``` From a5501c12ab4ab698bae5a0ea3ead8b8399ad418e Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Mon, 7 Aug 2023 10:43:16 +0200 Subject: [PATCH 147/170] [ISSUE 142] typo --- .../src/main/rules/EC2/python/EC2.asciidoc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ecocode-rules-specifications/src/main/rules/EC2/python/EC2.asciidoc b/ecocode-rules-specifications/src/main/rules/EC2/python/EC2.asciidoc index f9de6b834..e2688d834 100644 --- a/ecocode-rules-specifications/src/main/rules/EC2/python/EC2.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC2/python/EC2.asciidoc @@ -9,12 +9,12 @@ MATCH-CASE statement has a performance advantage over if – else. - ELSE statements use implicity variable names ! - one variable must be used maximum twice in IF / ELSEIF / ELSE statements at differents hierarchical levels - we can assume that if one variable is used three times or more, we should : -- use a MATCHS-CASE statement instead +- use a MATCH-CASE statement instead - or refactor the code if possible ## Non-compliant Code Example -NON compliant, because `nb` is used 4 times : +Non-compliant, because `nb` is used 4 times : - 2 explicit times in IF statements - 2 implicit times in ELSE statements From 25ebfc0be126afa8f580e86a96685d7025f0e2ca Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 8 Aug 2023 17:38:40 +0200 Subject: [PATCH 148/170] [ISSUE 142] update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd0ea72d4..3a8614061 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - [#121](https://github.com/green-code-initiative/ecoCode/issues/121) new PHP rule : Multiple if-else statement + refactoring implementation +- [#142](https://github.com/green-code-initiative/ecoCode/issues/1142) new Python rule : Multiple if-else statement + refactoring implementation ### Changed From 1eb998693375fe216ce80aa74a7571f378c8fc00 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 8 Aug 2023 19:06:57 +0200 Subject: [PATCH 149/170] [ISSUE 182] Python - remove python module becasue of moving to new repository --- .github/workflows/manual_release.yml | 21 -- .github/workflows/tag_release.yml | 21 -- CHANGELOG.md | 5 +- INSTALL.md | 9 +- README.md | 2 +- TODOs_DDC.md | 1 - docker-compose.yml | 3 - pom.xml | 18 - python-plugin/README.md | 1 - python-plugin/pom.xml | 130 ------- .../python/PythonPlugin.java | 28 -- .../python/PythonRuleRepository.java | 69 ---- .../python/checks/AvoidDoubleQuoteCheck.java | 24 -- .../python/checks/AvoidFullSQLRequest.java | 68 ---- .../python/checks/AvoidGettersAndSetters.java | 74 ---- .../AvoidGlobalVariableInFunctionCheck.java | 320 ------------------ .../AvoidListComprehensionInIterations.java | 71 ---- .../python/checks/AvoidSQLRequestInLoop.java | 84 ----- .../checks/AvoidTryCatchFinallyCheck.java | 27 -- .../AvoidUnoptimizedVectorImagesCheck.java | 72 ---- .../checks/DetectUnoptimizedImageFormat.java | 35 -- .../NoFunctionCallWhenDeclaringForLoop.java | 24 -- .../python/package-info.java | 21 -- .../python/PythonPluginTest.java | 42 --- .../python/PythonRuleRepositoryTest.java | 103 ------ .../python/checks/AvoidDoubleQuoteTest.java | 11 - .../checks/AvoidFullSQLRequestTest.java | 12 - .../checks/AvoidGettersAndSettersTest.java | 12 - ...voidGlobalVariableInFunctionCheckTest.java | 11 - ...voidListComprehensionInIterationsTest.java | 11 - .../checks/AvoidSQLRequestInLoopTest.java | 12 - .../checks/AvoidTryCatchFinallyCheckTest.java | 12 - .../AvoidUnoptimizedVectorImagesTest.java | 12 - .../DetectUnoptimizedImageFormatTest.java | 13 - ...oFunctionCallWhenDeclaringForLoopTest.java | 11 - .../AvoidListComprehensionInIterations.py | 35 -- .../resources/checks/avoidDoubleQuoteCheck.py | 13 - .../resources/checks/avoidFullSQLRequest.py | 10 - .../checks/avoidGettersAndSetters.py | 26 -- .../checks/avoidGlobalVariableInFunction.py | 43 --- .../resources/checks/avoidSQLRequestInLoop.py | 42 --- .../checks/avoidSQLRequestInLoopCheck.py | 83 ----- .../checks/avoidSQLRequestInLoopNoImports.py | 26 -- .../checks/avoidTryCatchFinallyCheck.py | 29 -- .../checks/avoidUnoptimizedVectorImages.py | 5 - .../checks/detectUnoptimizedImageFormat.py | 36 -- .../detectUnoptimizedImageFormatCompliant.py | 17 - .../src/test/resources/checks/init_dbtest.sql | 34 -- .../src/test/resources/checks/my.conf.sample | 5 - .../noFunctionCallWhenDeclaringForLoop.py | 9 - 50 files changed, 5 insertions(+), 1798 deletions(-) delete mode 100644 python-plugin/README.md delete mode 100644 python-plugin/pom.xml delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/PythonPlugin.java delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSetters.java delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheck.java delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoop.java delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoop.java delete mode 100644 python-plugin/src/main/java/fr/greencodeinitiative/python/package-info.java delete mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java delete mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java delete mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteTest.java delete mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequestTest.java delete mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSettersTest.java delete mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheckTest.java delete mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterationsTest.java delete mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoopTest.java delete mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheckTest.java delete mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesTest.java delete mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java delete mode 100644 python-plugin/src/test/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoopTest.java delete mode 100644 python-plugin/src/test/resources/checks/AvoidListComprehensionInIterations.py delete mode 100644 python-plugin/src/test/resources/checks/avoidDoubleQuoteCheck.py delete mode 100644 python-plugin/src/test/resources/checks/avoidFullSQLRequest.py delete mode 100644 python-plugin/src/test/resources/checks/avoidGettersAndSetters.py delete mode 100644 python-plugin/src/test/resources/checks/avoidGlobalVariableInFunction.py delete mode 100644 python-plugin/src/test/resources/checks/avoidSQLRequestInLoop.py delete mode 100644 python-plugin/src/test/resources/checks/avoidSQLRequestInLoopCheck.py delete mode 100644 python-plugin/src/test/resources/checks/avoidSQLRequestInLoopNoImports.py delete mode 100644 python-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck.py delete mode 100644 python-plugin/src/test/resources/checks/avoidUnoptimizedVectorImages.py delete mode 100644 python-plugin/src/test/resources/checks/detectUnoptimizedImageFormat.py delete mode 100644 python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatCompliant.py delete mode 100644 python-plugin/src/test/resources/checks/init_dbtest.sql delete mode 100644 python-plugin/src/test/resources/checks/my.conf.sample delete mode 100644 python-plugin/src/test/resources/checks/noFunctionCallWhenDeclaringForLoop.py diff --git a/.github/workflows/manual_release.yml b/.github/workflows/manual_release.yml index e3d225726..5b9292792 100644 --- a/.github/workflows/manual_release.yml +++ b/.github/workflows/manual_release.yml @@ -110,24 +110,3 @@ jobs: asset_path: lib/ecocode-php-plugin-${{ needs.build.outputs.last_tag }}.jar asset_name: ecocode-php-plugin-${{ needs.build.outputs.last_tag }}.jar asset_content_type: application/zip - upload-python: - name: Upload Python Plugin - runs-on: ubuntu-latest - needs: build - steps: - - name: Import plugin JAR files - id: import_jar_files - uses: actions/download-artifact@v3 - with: - name: ecocode-plugins - path: lib - - name: Upload Release Asset - Python Plugin - id: upload-release-asset - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{needs.build.outputs.upload_url}} - asset_path: lib/ecocode-python-plugin-${{ needs.build.outputs.last_tag }}.jar - asset_name: ecocode-python-plugin-${{ needs.build.outputs.last_tag }}.jar - asset_content_type: application/zip diff --git a/.github/workflows/tag_release.yml b/.github/workflows/tag_release.yml index ff213b10c..c71d22ed9 100644 --- a/.github/workflows/tag_release.yml +++ b/.github/workflows/tag_release.yml @@ -90,24 +90,3 @@ jobs: asset_path: lib/ecocode-php-plugin-${{ github.ref_name }}.jar asset_name: ecocode-php-plugin-${{ github.ref_name }}.jar asset_content_type: application/zip - upload-python: - name: Upload Python Plugin - runs-on: ubuntu-latest - needs: build - steps: - - name: Import plugin JAR files - id: import_jar_files - uses: actions/download-artifact@v3 - with: - name: ecocode-plugins - path: lib - - name: Upload Release Asset - Python Plugin - id: upload-release-asset - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{needs.build.outputs.upload_url}} - asset_path: lib/ecocode-python-plugin-${{ github.ref_name }}.jar - asset_name: ecocode-python-plugin-${{ github.ref_name }}.jar - asset_content_type: application/zip diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a8614061..2856e6d93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,13 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- [#121](https://github.com/green-code-initiative/ecoCode/issues/121) new PHP rule : Multiple if-else statement + refactoring implementation -- [#142](https://github.com/green-code-initiative/ecoCode/issues/1142) new Python rule : Multiple if-else statement + refactoring implementation - ### Changed ### Deleted +- [#182](https://github.com/green-code-initiative/ecoCode/issues/182) Split repository : move Python module to new `ecoCode-python` repository + ## [1.3.1] - 2023-07-19 ### Added diff --git a/INSTALL.md b/INSTALL.md index 46d6673fb..e4e1395cc 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -1,7 +1,5 @@ -- [Common installation notes / requirements](#common-installation-notes--requirements) -- [Special points for Standard plugins](#special-points-for-standard-plugins) - - [Project structure](#project-structure) - - [Plugin-specific guides](#plugin-specific-guides) +- [Project structure](#project-structure) +- [Plugin-specific guides](#plugin-specific-guides) Common installation notes / requirements ======================================== @@ -25,8 +23,6 @@ ecoCode # Root directory | +--php-plugin # PHP | -+--python-plugin # Python -| \--docker-compose.yml # Docker compose file ``` @@ -36,5 +32,4 @@ Plugin-specific guides ---------------------- - [Java how-to](java-plugin/README.md) -- [Python how-to](python-plugin/README.md) - [PHP how-to](php-plugin/README.md) diff --git a/README.md b/README.md index 7a7be356b..40b803849 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ refer to the contribution section. - [Java](java-plugin/) - [JavaScript](https://github.com/green-code-initiative/ecoCode-javascript) - [PHP](php-plugin/) -- [Python](python-plugin/) +- [Python](https://github.com/green-code-initiative/ecoCode-python) ![Screenshot](docs/resources/screenshot.PNG) diff --git a/TODOs_DDC.md b/TODOs_DDC.md index 1cec0dede..43c7dc222 100644 --- a/TODOs_DDC.md +++ b/TODOs_DDC.md @@ -12,7 +12,6 @@ actions vues perso : - ménage dans les branches de dev (local et remote) - JYC : suppression dépendance analyser-commons ==> check si bien tout nettoyé (version dans pom, référence dans code) - créer issue sur la rule EC2 (`avoidMultipleIfElse`) sur JAVA : - - à refondre avec les uses cases du PHP + implem du PHP (en cours - PR_160_recup) - JAVA : existe depuis longtemps !!! normal que l'implem PHP et python aient le même code minimaliste fonctionellement - voir les rules désativées chez PJ, créer des issues et corriger (`avoidMultipleIfElse`) : - voir pourquoi désactivées car ralaient trop diff --git a/docker-compose.yml b/docker-compose.yml index 7d6d0159d..9240b111a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -21,9 +21,6 @@ services: - type: bind source: ./php-plugin/target/ecocode-php-plugin-1.3.2-SNAPSHOT.jar target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.3.2-SNAPSHOT.jar - - type: bind - source: ./python-plugin/target/ecocode-python-plugin-1.3.2-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-python-plugin-1.3.2-SNAPSHOT.jar - "extensions:/opt/sonarqube/extensions" - "logs:/opt/sonarqube/logs" - "data:/opt/sonarqube/data" diff --git a/pom.xml b/pom.xml index 1f7d02e26..1bd493c7b 100644 --- a/pom.xml +++ b/pom.xml @@ -79,7 +79,6 @@ ecocode-rules-specifications - python-plugin java-plugin php-plugin @@ -110,7 +109,6 @@ 9.4.0.54424 7.19.0.31550 - 4.3.0.11660 3.29.0.9684 2.5.0.1358 @@ -168,15 +166,6 @@ provided - - - org.sonarsource.python - sonar-python-plugin - ${sonarpython.version} - sonar-plugin - provided - - org.sonarsource.java @@ -206,13 +195,6 @@ test - - org.sonarsource.python - python-checks-testkit - ${sonarpython.version} - test - - diff --git a/python-plugin/README.md b/python-plugin/README.md deleted file mode 100644 index 4e77f52dc..000000000 --- a/python-plugin/README.md +++ /dev/null @@ -1 +0,0 @@ -https://github.com/SonarSource/sonar-custom-rules-examples/tree/master/python-custom-rules \ No newline at end of file diff --git a/python-plugin/pom.xml b/python-plugin/pom.xml deleted file mode 100644 index 5da4fcb52..000000000 --- a/python-plugin/pom.xml +++ /dev/null @@ -1,130 +0,0 @@ - - - 4.0.0 - - - io.ecocode - ecocode-parent - 1.3.2-SNAPSHOT - - - ecocode-python-plugin - sonar-plugin - - ecoCode - Python language - Provides rules to reduce the environmental footprint of your Python programs - https://github.com/green-code-initiative/ecoCode/tree/main/python-plugin - - - - ${project.groupId} - ecocode-rules-specifications - ${project.version} - python - - - - org.sonarsource.python - sonar-python-plugin - sonar-plugin - provided - - - - org.sonarsource.sonarqube - sonar-plugin-api - provided - - - - - - - - - - org.sonarsource.python - python-checks-testkit - test - - - - org.mockito - mockito-junit-jupiter - test - - - - - - - - org.sonarsource.sonar-packaging-maven-plugin - sonar-packaging-maven-plugin - true - - ecocodepython - ${project.name} - fr.greencodeinitiative.python.PythonPlugin - true - ${sonarqube.version} - ${java.version} - - - - - org.apache.maven.plugins - maven-shade-plugin - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-bundle - package - - copy - - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - jar - true - - - ../lib - - - - - - org.jacoco - jacoco-maven-plugin - - - file - false - - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - - - - diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonPlugin.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonPlugin.java deleted file mode 100644 index cb8012554..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonPlugin.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2023 Green Code Initiative - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.python; - -import org.sonar.api.Plugin; - -public class PythonPlugin implements Plugin { - - @Override - public void define(Context context) { - context.addExtension(PythonRuleRepository.class); - } - -} diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java deleted file mode 100644 index 23ff4f51e..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/PythonRuleRepository.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2023 Green Code Initiative - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.python; - -import fr.greencodeinitiative.python.checks.*; -import org.sonar.api.SonarRuntime; -import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.plugins.python.api.PythonCustomRuleRepository; -import org.sonarsource.analyzer.commons.RuleMetadataLoader; - -import java.util.Arrays; -import java.util.List; - -public class PythonRuleRepository implements RulesDefinition, PythonCustomRuleRepository { - - public static final String LANGUAGE = "py"; - public static final String NAME = "ecoCode"; - public static final String RESOURCE_BASE_PATH = "io/ecocode/rules/python"; - public static final String REPOSITORY_KEY = "ecocode-python"; - - private final SonarRuntime sonarRuntime; - - public PythonRuleRepository(SonarRuntime sonarRuntime) { - this.sonarRuntime = sonarRuntime; - } - - @Override - public void define(Context context) { - NewRepository repository = context.createRepository(REPOSITORY_KEY, LANGUAGE).setName(NAME); - RuleMetadataLoader ruleMetadataLoader = new RuleMetadataLoader(RESOURCE_BASE_PATH, sonarRuntime); - ruleMetadataLoader.addRulesByAnnotatedClass(repository, (List) checkClasses()); - repository.done(); - } - - @Override - public String repositoryKey() { - return REPOSITORY_KEY; - } - - @Override - public List checkClasses() { - return Arrays.asList( - AvoidDoubleQuoteCheck.class, - AvoidGettersAndSetters.class, - AvoidGlobalVariableInFunctionCheck.class, - AvoidSQLRequestInLoop.class, - AvoidTryCatchFinallyCheck.class, - AvoidUnoptimizedVectorImagesCheck.class, - NoFunctionCallWhenDeclaringForLoop.class, - AvoidFullSQLRequest.class, - AvoidListComprehensionInIterations.class, - DetectUnoptimizedImageFormat.class - ); - } -} diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java deleted file mode 100644 index e6b191289..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteCheck.java +++ /dev/null @@ -1,24 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.sonar.check.Rule; -import org.sonar.plugins.python.api.PythonSubscriptionCheck; -import org.sonar.plugins.python.api.SubscriptionContext; -import org.sonar.plugins.python.api.tree.StringLiteral; -import org.sonar.plugins.python.api.tree.Tree; - -@Rule(key = "EC66") -public class AvoidDoubleQuoteCheck extends PythonSubscriptionCheck { - public static final String MESSAGE_RULE = "Avoid using quotation mark (\"), prefer using simple quote (')"; - @Override - public void initialize(Context context) { - context.registerSyntaxNodeConsumer(Tree.Kind.STRING_LITERAL, this::visitNodeString); - } - - private void visitNodeString(SubscriptionContext subscriptionContext) { - StringLiteral stringLiteral = (StringLiteral) subscriptionContext.syntaxNode(); - - if (!stringLiteral.stringElements().isEmpty() && stringLiteral.stringElements().get(0).value().startsWith("\"")){ - subscriptionContext.addIssue(stringLiteral, MESSAGE_RULE); - } - } -} diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java deleted file mode 100644 index 8c6d4eedf..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequest.java +++ /dev/null @@ -1,68 +0,0 @@ -package fr.greencodeinitiative.python.checks; - - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Pattern; - -import org.sonar.check.Rule; -import org.sonar.plugins.python.api.PythonSubscriptionCheck; -import org.sonar.plugins.python.api.SubscriptionContext; -import org.sonar.plugins.python.api.tree.StringElement; -import org.sonar.plugins.python.api.tree.StringLiteral; -import org.sonar.plugins.python.api.tree.Tree; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC74") -@DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "S74") -public class AvoidFullSQLRequest extends PythonSubscriptionCheck { - - protected static final String MESSAGERULE = "Don't use the query SELECT * FROM"; - - // TODO DDC : create support to add in deployment th dependency com.google.re2j:re2j - // and replace "import java.util.regex.Pattern" by "import com.google.re2j.Pattern" - private static final Pattern PATTERN = Pattern.compile("(?i).*select.*\\*.*from.*"); - private static final Map> linesWithIssuesByFile = new HashMap<>(); - - - @Override - public void initialize(Context context) { - context.registerSyntaxNodeConsumer(Tree.Kind.STRING_LITERAL, this::visitNodeString); - } - - public void visitNodeString(SubscriptionContext ctx) { - StringLiteral stringLiteral = (StringLiteral) ctx.syntaxNode(); - stringLiteral.stringElements().forEach(stringElement -> checkIssue(stringElement, ctx)); - } - - public void checkIssue(StringElement stringElement, SubscriptionContext ctx) { - if (lineAlreadyHasThisIssue(stringElement, ctx)) return; - if (PATTERN.matcher(stringElement.value()).matches()) { - repport(stringElement, ctx); - } - } - - private void repport(StringElement stringElement, SubscriptionContext ctx) { - if (stringElement.firstToken() != null) { - final String classname = ctx.pythonFile().fileName(); - final int line = stringElement.firstToken().line(); - linesWithIssuesByFile.computeIfAbsent(classname, k -> new ArrayList<>()); - linesWithIssuesByFile.get(classname).add(line); - } - ctx.addIssue(stringElement, MESSAGERULE); - } - - private boolean lineAlreadyHasThisIssue(StringElement stringElement, SubscriptionContext ctx) { - if (stringElement.firstToken() != null) { - final String filename = ctx.pythonFile().fileName(); - final int line = stringElement.firstToken().line(); - - return linesWithIssuesByFile.containsKey(filename) - && linesWithIssuesByFile.get(filename).contains(line); - } - - return false; - } -} diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSetters.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSetters.java deleted file mode 100644 index beb063de7..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSetters.java +++ /dev/null @@ -1,74 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import java.util.List; -import java.util.stream.Collectors; - -import org.sonar.check.Rule; -import org.sonar.plugins.python.api.PythonSubscriptionCheck; -import org.sonar.plugins.python.api.SubscriptionContext; -import org.sonar.plugins.python.api.tree.AnyParameter; -import org.sonar.plugins.python.api.tree.AssignmentStatement; -import org.sonar.plugins.python.api.tree.FunctionDef; -import org.sonar.plugins.python.api.tree.ParameterList; -import org.sonar.plugins.python.api.tree.QualifiedExpression; -import org.sonar.plugins.python.api.tree.ReturnStatement; -import org.sonar.plugins.python.api.tree.Statement; -import org.sonar.plugins.python.api.tree.StatementList; -import org.sonar.plugins.python.api.tree.Tree; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC7") -@DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "D7") -public class AvoidGettersAndSetters extends PythonSubscriptionCheck { - - public static final String DESCRIPTION = "Avoid creating getter and setter methods in classes"; - - @Override - public void initialize(Context context) { - context.registerSyntaxNodeConsumer(Tree.Kind.FUNCDEF, ctx -> { - FunctionDef functionDef = (FunctionDef) ctx.syntaxNode(); - StatementList statementList = functionDef.body(); - List statements = statementList.statements(); - if (functionDef.parent().parent().is(Tree.Kind.CLASSDEF)) { - checkAllGetters(statements, functionDef, ctx); - checkAllSetters(statements, functionDef, ctx); - } - }); - } - - public void checkAllSetters(List statements, FunctionDef functionDef, SubscriptionContext ctx) { - if (statements.size() == 1 && statements.get(0).is(Tree.Kind.ASSIGNMENT_STMT)) { - AssignmentStatement assignmentStatement = (AssignmentStatement) statements.get(0); - if (checkIfStatementIsQualifiedExpressionAndStartsWithSelfDot((QualifiedExpression) assignmentStatement.children().get(0).children().get(0))) { - // Check if assignedValue is a parameter of the function - ParameterList parameters = functionDef.parameters(); - if (parameters != null && !parameters.all().stream().filter(p -> checkAssignementFromParameter(assignmentStatement, p)).collect(Collectors.toList()).isEmpty()) { - ctx.addIssue(functionDef.defKeyword(), AvoidGettersAndSetters.DESCRIPTION); - } - } - } - } - - public void checkAllGetters(List statements, FunctionDef functionDef, SubscriptionContext ctx) { - Statement lastStatement = statements.get(statements.size() - 1); - if (lastStatement.is(Tree.Kind.RETURN_STMT)) { - List returnStatementChildren = ((ReturnStatement) lastStatement).children(); - if (returnStatementChildren.get(1).is(Tree.Kind.QUALIFIED_EXPR) && - checkIfStatementIsQualifiedExpressionAndStartsWithSelfDot((QualifiedExpression) returnStatementChildren.get(1))) { - ctx.addIssue(functionDef.defKeyword(), AvoidGettersAndSetters.DESCRIPTION); - } - } - } - - public boolean checkAssignementFromParameter(AssignmentStatement assignmentStatement, AnyParameter parameter) { - String parameterToString = parameter.firstToken().value(); - return assignmentStatement.assignedValue().firstToken().value().equalsIgnoreCase(parameterToString); - } - - public boolean checkIfStatementIsQualifiedExpressionAndStartsWithSelfDot(QualifiedExpression qualifiedExpression) { - List qualifedExpressionChildren = qualifiedExpression.children(); - return qualifedExpressionChildren.size() == 3 && - qualifedExpressionChildren.get(0).firstToken().value().equalsIgnoreCase("self") && - qualifedExpressionChildren.get(1).firstToken().value().equalsIgnoreCase("."); - } -} diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheck.java deleted file mode 100644 index 82bc46b74..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheck.java +++ /dev/null @@ -1,320 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.sonar.check.Rule; -import org.sonar.plugins.python.api.PythonSubscriptionCheck; -import org.sonar.plugins.python.api.SubscriptionCheck; -import org.sonar.plugins.python.api.SubscriptionContext; -import org.sonar.plugins.python.api.symbols.Symbol; -import org.sonar.plugins.python.api.tree.AnnotatedAssignment; -import org.sonar.plugins.python.api.tree.ArgList; -import org.sonar.plugins.python.api.tree.AssertStatement; -import org.sonar.plugins.python.api.tree.AssignmentExpression; -import org.sonar.plugins.python.api.tree.AssignmentStatement; -import org.sonar.plugins.python.api.tree.AwaitExpression; -import org.sonar.plugins.python.api.tree.BinaryExpression; -import org.sonar.plugins.python.api.tree.CallExpression; -import org.sonar.plugins.python.api.tree.CompoundAssignmentStatement; -import org.sonar.plugins.python.api.tree.ComprehensionExpression; -import org.sonar.plugins.python.api.tree.ComprehensionFor; -import org.sonar.plugins.python.api.tree.ComprehensionIf; -import org.sonar.plugins.python.api.tree.ConditionalExpression; -import org.sonar.plugins.python.api.tree.DictCompExpression; -import org.sonar.plugins.python.api.tree.DictionaryLiteral; -import org.sonar.plugins.python.api.tree.ElseClause; -import org.sonar.plugins.python.api.tree.ExceptClause; -import org.sonar.plugins.python.api.tree.ExecStatement; -import org.sonar.plugins.python.api.tree.ExpressionList; -import org.sonar.plugins.python.api.tree.ExpressionStatement; -import org.sonar.plugins.python.api.tree.FileInput; -import org.sonar.plugins.python.api.tree.FinallyClause; -import org.sonar.plugins.python.api.tree.ForStatement; -import org.sonar.plugins.python.api.tree.FunctionDef; -import org.sonar.plugins.python.api.tree.IfStatement; -import org.sonar.plugins.python.api.tree.KeyValuePair; -import org.sonar.plugins.python.api.tree.LambdaExpression; -import org.sonar.plugins.python.api.tree.ListLiteral; -import org.sonar.plugins.python.api.tree.Name; -import org.sonar.plugins.python.api.tree.Parameter; -import org.sonar.plugins.python.api.tree.ParameterList; -import org.sonar.plugins.python.api.tree.ParenthesizedExpression; -import org.sonar.plugins.python.api.tree.PrintStatement; -import org.sonar.plugins.python.api.tree.RaiseStatement; -import org.sonar.plugins.python.api.tree.RegularArgument; -import org.sonar.plugins.python.api.tree.ReprExpression; -import org.sonar.plugins.python.api.tree.ReturnStatement; -import org.sonar.plugins.python.api.tree.SetLiteral; -import org.sonar.plugins.python.api.tree.StatementList; -import org.sonar.plugins.python.api.tree.SubscriptionExpression; -import org.sonar.plugins.python.api.tree.Tree; -import org.sonar.plugins.python.api.tree.TryStatement; -import org.sonar.plugins.python.api.tree.Tuple; -import org.sonar.plugins.python.api.tree.TupleParameter; -import org.sonar.plugins.python.api.tree.UnaryExpression; -import org.sonar.plugins.python.api.tree.UnpackingExpression; -import org.sonar.plugins.python.api.tree.WhileStatement; -import org.sonar.plugins.python.api.tree.YieldExpression; -import org.sonar.plugins.python.api.tree.YieldStatement; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC4") -@DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "D4") -public class AvoidGlobalVariableInFunctionCheck extends PythonSubscriptionCheck { - - public static final String DESCRIPTION = "Use local variable (function/class scope) instead of global variable (application scope)"; - - private List globalVariables; - private List definedLocalVariables; - private Map usedLocalVariables; - - @Override - public void initialize(SubscriptionCheck.Context context) { - globalVariables = new ArrayList<>(); - context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, this::visitFileInput); - context.registerSyntaxNodeConsumer(Tree.Kind.FUNCDEF, this::visitFuncDef); - } - - public void visitFileInput(SubscriptionContext ctx) { - FileInput fileInput = (FileInput) ctx.syntaxNode(); - fileInput.globalVariables().stream().filter(v -> v.is(Symbol.Kind.OTHER)).forEach(v -> this.globalVariables.add(v.name())); - } - - void visitFuncDef(SubscriptionContext ctx) { - this.definedLocalVariables = new ArrayList<>(); - this.usedLocalVariables = new HashMap<>(); - - FunctionDef functionDef = (FunctionDef) ctx.syntaxNode(); - - ParameterList parameterList = functionDef.parameters(); - if (parameterList != null) { - parameterList.nonTuple().forEach(p -> extractVariablesFromExpression(p, true)); - } - - functionDef.body().statements() - .forEach(s -> extractVariablesFromExpression(s, false)); - - this.usedLocalVariables.entrySet().stream() - .filter(e -> !this.definedLocalVariables.contains(e.getValue()) && this.globalVariables.contains(e.getValue())) - .forEach(e -> ctx.addIssue(e.getKey(), DESCRIPTION)); - } - - void extractVariablesFromExpression(Tree element, boolean isAssigned) { - if (element == null) { - return; - } - - switch (element.getKind()) { - case REGULAR_ARGUMENT: - extractVariablesFromExpression(((RegularArgument) element).expression(), isAssigned); - break; - case ARG_LIST: - ((ArgList) element).arguments().forEach(a -> extractVariablesFromExpression(a, isAssigned)); - break; - case ANNOTATED_ASSIGNMENT: - AnnotatedAssignment annotatedAssignment = (AnnotatedAssignment) element; - extractVariablesFromExpression(annotatedAssignment.variable(), true); - extractVariablesFromExpression(annotatedAssignment.assignedValue(), false); - break; - case ASSERT_STMT: - AssertStatement assertStatement = (AssertStatement) element; - extractVariablesFromExpression(assertStatement.condition(), false); - extractVariablesFromExpression(assertStatement.message(), false); - break; - case ASSIGNMENT_STMT: - AssignmentStatement assignmentStatement = (AssignmentStatement) element; - assignmentStatement.lhsExpressions().forEach(e -> extractVariablesFromExpression(e, true)); - extractVariablesFromExpression(assignmentStatement.assignedValue(), false); - break; - case CALL_EXPR: - extractVariablesFromExpression(((CallExpression) element).argumentList(), isAssigned); - break; - case CONDITIONAL_EXPR: - ConditionalExpression conditionalExpression = (ConditionalExpression) element; - extractVariablesFromExpression(conditionalExpression.trueExpression(), isAssigned); - extractVariablesFromExpression(conditionalExpression.falseExpression(), false); - extractVariablesFromExpression(conditionalExpression.condition(), isAssigned); - break; - case COMPOUND_ASSIGNMENT: - CompoundAssignmentStatement compoundAssignmentStatement = (CompoundAssignmentStatement) element; - extractVariablesFromExpression(compoundAssignmentStatement.lhsExpression(), true); - extractVariablesFromExpression(compoundAssignmentStatement.rhsExpression(), false); - break; - case DICTIONARY_LITERAL: - ((DictionaryLiteral) element).elements().forEach(e -> extractVariablesFromExpression(e, false)); - break; - case ELSE_CLAUSE: - extractVariablesFromExpression(((ElseClause) element).body(), isAssigned); - break; - case EXCEPT_CLAUSE: - extractVariablesFromExpression(((ExceptClause) element).body(), isAssigned); - break; - case EXEC_STMT: - ExecStatement execStatement = (ExecStatement) element; - extractVariablesFromExpression(execStatement.expression(), isAssigned); - extractVariablesFromExpression(execStatement.globalsExpression(), isAssigned); - extractVariablesFromExpression(execStatement.localsExpression(), isAssigned); - break; - case EXPRESSION_LIST: - ((ExpressionList) element).expressions().forEach(e -> extractVariablesFromExpression(e, isAssigned)); - break; - case EXPRESSION_STMT: - ((ExpressionStatement) element).expressions().forEach(e -> extractVariablesFromExpression(e, isAssigned)); - break; - case FILE_INPUT: - extractVariablesFromExpression(((FileInput) element).statements(), isAssigned); - break; - case FINALLY_CLAUSE: - extractVariablesFromExpression(((FinallyClause) element).body(), isAssigned); - break; - case FOR_STMT: - ForStatement forStatement = ((ForStatement) element); - forStatement.expressions().forEach(e -> extractVariablesFromExpression(e, true)); - forStatement.testExpressions().forEach(e -> extractVariablesFromExpression(e, false)); - extractVariablesFromExpression(forStatement.body(), isAssigned); - extractVariablesFromExpression(forStatement.elseClause(), isAssigned); - break; - case IF_STMT: - IfStatement ifStatement = (IfStatement) element; - extractVariablesFromExpression(ifStatement.condition(), false); - extractVariablesFromExpression(ifStatement.body(), isAssigned); - extractVariablesFromExpression(ifStatement.elseBranch(), isAssigned); - ifStatement.elifBranches().forEach(b -> extractVariablesFromExpression(b, isAssigned)); - break; - case LAMBDA: - extractVariablesFromExpression(((LambdaExpression) element).expression(), isAssigned); - break; - case LIST_LITERAL: - extractVariablesFromExpression(((ListLiteral) element).elements(), false); - break; - case NAME: - if (isAssigned) { - this.definedLocalVariables.add(((Name) element).name()); - } else { - this.usedLocalVariables.put(element, ((Name) element).name()); - } - break; - case PRINT_STMT: - ((PrintStatement) element).expressions().forEach(e -> extractVariablesFromExpression(e, false)); - break; - case RAISE_STMT: - RaiseStatement raiseStatement = (RaiseStatement) element; - extractVariablesFromExpression(raiseStatement.fromExpression(), false); - raiseStatement.expressions().forEach(e -> extractVariablesFromExpression(e, false)); - break; - case REPR: - extractVariablesFromExpression(((ReprExpression) element).expressionList(), isAssigned); - break; - case RETURN_STMT: - ((ReturnStatement) element).expressions().forEach(e -> extractVariablesFromExpression(e, false)); - break; - case SET_LITERAL: - ((SetLiteral) element).elements().forEach(e -> extractVariablesFromExpression(e, false)); - break; - case STATEMENT_LIST: - ((StatementList) element).statements().forEach(s -> extractVariablesFromExpression(s, isAssigned)); - break; - case TRY_STMT: - TryStatement tryStatement = (TryStatement) element; - extractVariablesFromExpression(tryStatement.body(), isAssigned); - tryStatement.exceptClauses().forEach(c -> extractVariablesFromExpression(c, isAssigned)); - extractVariablesFromExpression(tryStatement.elseClause(), isAssigned); - extractVariablesFromExpression(tryStatement.finallyClause(), isAssigned); - break; - case PARAMETER: - Parameter parameter = (Parameter) element; - extractVariablesFromExpression(parameter.name(), true); - extractVariablesFromExpression(parameter.defaultValue(), false); - break; - case TUPLE_PARAMETER: - ((TupleParameter) element).parameters().forEach(p -> extractVariablesFromExpression(p, isAssigned)); - break; - case PARAMETER_LIST: - ((ParameterList) element).all().forEach(a -> extractVariablesFromExpression(a, true)); - break; - case WHILE_STMT: - WhileStatement whileStatement = (WhileStatement) element; - extractVariablesFromExpression(whileStatement.condition(), false); - extractVariablesFromExpression(whileStatement.body(), isAssigned); - extractVariablesFromExpression(whileStatement.elseClause(), isAssigned); - break; - case YIELD_EXPR: - ((YieldExpression) element).expressions().forEach(e -> extractVariablesFromExpression(e, isAssigned)); - break; - case YIELD_STMT: - extractVariablesFromExpression(((YieldStatement) element).yieldExpression(), isAssigned); - break; - case PARENTHESIZED: - extractVariablesFromExpression(((ParenthesizedExpression) element).expression(), isAssigned); - break; - case UNPACKING_EXPR: - extractVariablesFromExpression(((UnpackingExpression) element).expression(), isAssigned); - break; - case AWAIT: - extractVariablesFromExpression(((AwaitExpression) element).expression(), false); - break; - case TUPLE: - ((Tuple) element).elements().forEach(e -> extractVariablesFromExpression(e, isAssigned)); - break; - case DICT_COMPREHENSION: - extractVariablesFromExpression(((DictCompExpression) element).comprehensionFor(), false); - break; - case LIST_COMPREHENSION: - case SET_COMPREHENSION: - case GENERATOR_EXPR: - extractVariablesFromExpression(((ComprehensionExpression) element).resultExpression(), false); - extractVariablesFromExpression(((ComprehensionExpression) element).comprehensionFor(), true); - break; - case COMP_FOR: - extractVariablesFromExpression(((ComprehensionFor) element).loopExpression(), true); - extractVariablesFromExpression(((ComprehensionFor) element).iterable(), false); - break; - case COMP_IF: - extractVariablesFromExpression(((ComprehensionIf) element).condition(), false); - break; - case SUBSCRIPTION: - extractVariablesFromExpression(((SubscriptionExpression) element).object(), false); - extractVariablesFromExpression(((SubscriptionExpression) element).subscripts(), false); - break; - case PLUS: - case MINUS: - case MULTIPLICATION: - case DIVISION: - case FLOOR_DIVISION: - case MODULO: - case MATRIX_MULTIPLICATION: - case SHIFT_EXPR: - case BITWISE_AND: - case BITWISE_OR: - case BITWISE_XOR: - case AND: - case OR: - case COMPARISON: - case POWER: - BinaryExpression binaryExpression = (BinaryExpression) element; - extractVariablesFromExpression(binaryExpression.leftOperand(), false); - extractVariablesFromExpression(binaryExpression.rightOperand(), false); - break; - case UNARY_PLUS: - case UNARY_MINUS: - case BITWISE_COMPLEMENT: - case NOT: - extractVariablesFromExpression(((UnaryExpression) element).expression(), false); - break; - case ASSIGNMENT_EXPRESSION: - AssignmentExpression assignmentExpression = (AssignmentExpression) element; - extractVariablesFromExpression(assignmentExpression.lhsName(), true); - extractVariablesFromExpression(assignmentExpression.expression(), false); - break; - case KEY_VALUE_PAIR: - KeyValuePair keyValuePair = (KeyValuePair) element; - extractVariablesFromExpression(keyValuePair.key(), true); - extractVariablesFromExpression(keyValuePair.value(), false); - break; - default: - } - } -} diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java deleted file mode 100644 index 917d053c9..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterations.java +++ /dev/null @@ -1,71 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.sonar.check.Rule; -import org.sonar.plugins.python.api.PythonSubscriptionCheck; -import org.sonar.plugins.python.api.SubscriptionContext; -import org.sonar.plugins.python.api.symbols.Symbol; -import org.sonar.plugins.python.api.tree.Expression; -import org.sonar.plugins.python.api.tree.CallExpression; -import org.sonar.plugins.python.api.tree.ForStatement; -import org.sonar.plugins.python.api.tree.Tree; -import org.sonar.plugins.python.api.tree.RegularArgument; - -import java.util.Objects; - -import static org.sonar.plugins.python.api.tree.Tree.Kind.CALL_EXPR; -import static org.sonar.plugins.python.api.tree.Tree.Kind.FOR_STMT; -import static org.sonar.plugins.python.api.tree.Tree.Kind.LIST_COMPREHENSION; -import static org.sonar.plugins.python.api.tree.Tree.Kind.REGULAR_ARGUMENT; - -@Rule(key = "EC404") -public class AvoidListComprehensionInIterations extends PythonSubscriptionCheck { - - public static final String DESCRIPTION = "Use generator comprehension instead of list comprehension in for loop declaration"; - - @Override - public void initialize(Context context) { - context.registerSyntaxNodeConsumer(FOR_STMT, this::visitIteration); - } - - private void visitIteration(SubscriptionContext context) { - ForStatement forStatement = (ForStatement) context.syntaxNode(); - - Expression forTestExpression = forStatement.testExpressions().get(0); - if (forTestExpression.is(LIST_COMPREHENSION)) { - context.addIssue(forTestExpression.firstToken(), DESCRIPTION); - } else if (forTestExpression.is(CALL_EXPR)) { - CallExpression callExpression = (CallExpression) forTestExpression; - visitCallExpression(context, callExpression); - } - } - - private void visitCallExpression(SubscriptionContext context, CallExpression callExpression){ - switch (getFunctionNameFromCallExpression(callExpression)) { - case "zip": - case "filter": - case "enumerate": - Objects.requireNonNull(callExpression.argumentList()). - arguments().forEach(e -> visitFunctionArgument(context, e)); - break; - default: - break; - } - } - - private void visitFunctionArgument(SubscriptionContext context, Tree argument) { - if (argument.is(REGULAR_ARGUMENT)) { - Expression expression = ((RegularArgument)argument).expression(); - if (expression.is(LIST_COMPREHENSION)) { - context.addIssue(expression.firstToken(), DESCRIPTION); - } else if (expression.is(CALL_EXPR)) { - CallExpression callExpression = (CallExpression) expression; - visitCallExpression(context, callExpression); - } - } - } - - private String getFunctionNameFromCallExpression(CallExpression callExpression) { - Symbol symbol = callExpression.calleeSymbol(); - return symbol != null && symbol.name() != null ? symbol.name() : ""; - } -} diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoop.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoop.java deleted file mode 100644 index a2bb20786..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoop.java +++ /dev/null @@ -1,84 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -import org.sonar.check.Rule; -import org.sonar.plugins.python.api.PythonSubscriptionCheck; -import org.sonar.plugins.python.api.SubscriptionContext; -import org.sonar.plugins.python.api.symbols.Symbol; -import org.sonar.plugins.python.api.tree.AliasedName; -import org.sonar.plugins.python.api.tree.BaseTreeVisitor; -import org.sonar.plugins.python.api.tree.CallExpression; -import org.sonar.plugins.python.api.tree.FileInput; -import org.sonar.plugins.python.api.tree.Name; -import org.sonar.plugins.python.api.tree.QualifiedExpression; -import org.sonar.plugins.python.api.tree.Tree; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC72") -@DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "S72") -public class AvoidSQLRequestInLoop extends PythonSubscriptionCheck { - - // TODO: Handle ORM lib - private static final List SQL_LIBS = Arrays.asList("cx_Oracle", "mysql.connector", "psycopg2", "pymssql", "pyodbc", "sqlite3"); - - protected static final String MESSAGE_RULE = "Avoid performing SQL queries within a loop"; - - private boolean isUsingSqlLib = false; - - @Override - public void initialize(Context context) { - context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, this::visitFile); - context.registerSyntaxNodeConsumer(Tree.Kind.CALL_EXPR, this::checkCallExpression); - } - - private void visitFile(SubscriptionContext ctx) { - FileInput tree = (FileInput) ctx.syntaxNode(); - SymbolsFromImport visitor = new SymbolsFromImport(); - tree.accept(visitor); - visitor.symbols.stream() - .filter(Objects::nonNull) - .map(Symbol::fullyQualifiedName) - .filter(Objects::nonNull) - .forEach(qualifiedName -> { - if (SQL_LIBS.contains(qualifiedName)) { - isUsingSqlLib = true; - } - }); - } - - private static class SymbolsFromImport extends BaseTreeVisitor { - private final Set symbols = new HashSet<>(); - - @Override - public void visitAliasedName(AliasedName aliasedName) { - List names = aliasedName.dottedName().names(); - symbols.add(names.get(names.size() - 1).symbol()); - } - } - - private void checkCallExpression(SubscriptionContext context) { - CallExpression expression = (CallExpression) context.syntaxNode(); - - if (expression.callee().is(Tree.Kind.QUALIFIED_EXPR)) { - String name = ((QualifiedExpression) expression.callee()).name().name(); - if (isUsingSqlLib && "execute".equals(name) && hasLoopParent(expression)) { - context.addIssue(expression, AvoidSQLRequestInLoop.MESSAGE_RULE); - } - } - } - - private boolean hasLoopParent(Tree tree) { - for (Tree parent = tree.parent(); parent != null; parent = parent.parent()) { - Tree.Kind kind = parent.getKind(); - if (kind == Tree.Kind.FOR_STMT || kind == Tree.Kind.WHILE_STMT) { - return true; - } - } - return false; - } -} diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java deleted file mode 100644 index be801c44d..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheck.java +++ /dev/null @@ -1,27 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.sonar.check.Rule; -import org.sonar.plugins.python.api.PythonSubscriptionCheck; -import org.sonar.plugins.python.api.SubscriptionContext; -import org.sonar.plugins.python.api.tree.Tree; -import org.sonar.plugins.python.api.tree.TryStatement; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC34") -@DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "S34") -public class AvoidTryCatchFinallyCheck extends PythonSubscriptionCheck { - - public static final String DESCRIPTION = "Avoid the use of try-catch"; - - @Override - public void initialize(Context context) { - context.registerSyntaxNodeConsumer(Tree.Kind.TRY_STMT, this::visitNode); - } - - public void visitNode(SubscriptionContext ctx) { - TryStatement tryStatement = (TryStatement) ctx.syntaxNode(); - ctx.addIssue(tryStatement.tryKeyword(), DESCRIPTION); - - } - -} diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java deleted file mode 100644 index f3a9c3686..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesCheck.java +++ /dev/null @@ -1,72 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.sonar.check.Rule; -import org.sonar.plugins.python.api.PythonSubscriptionCheck; -import org.sonar.plugins.python.api.SubscriptionContext; -import org.sonar.plugins.python.api.tree.*; - -@Rule(key = "EC10") -public class AvoidUnoptimizedVectorImagesCheck extends PythonSubscriptionCheck { - - public static final String DESCRIPTION = "Avoid using unoptimized vector images"; - private static final Pattern LAYERS_PATTERN = Pattern.compile(""); - - @Override - public void initialize(Context ctx) { - ctx.registerSyntaxNodeConsumer(Tree.Kind.STRING_ELEMENT, this::checkSVG); - } - - private void checkSVG(SubscriptionContext ctx) { - StringElement stringLiteral = (StringElement) ctx.syntaxNode(); - checkComments(stringLiteral, ctx); - checkLayers(stringLiteral, ctx); - checkNamespaces(stringLiteral, ctx); - checkMetadata(stringLiteral, ctx); - } - - private void checkComments(StringElement str, SubscriptionContext ctx) { - if (isSvgTagNotDetected(str)) - return; - - if (str.value().contains("")) { - ctx.addIssue(str, DESCRIPTION); - } - } - - private void checkLayers(StringElement str, SubscriptionContext ctx) { - if (isSvgTagNotDetected(str)) - return; - - Matcher matcher = LAYERS_PATTERN.matcher(str.value()); - int matches = 0; - while (matcher.find()) matches++; - if (matches > 1) { // if at least 2 finds, create an issue - ctx.addIssue(str, DESCRIPTION); - } - } - - private void checkNamespaces(StringElement str, SubscriptionContext ctx) { - if (isSvgTagNotDetected(str)) - return; - - if (str.value().contains("xmlns:") && !str.value().contains("xmlns:svg=")) { - ctx.addIssue(str, DESCRIPTION); - } - } - - private void checkMetadata(StringElement str, SubscriptionContext ctx) { - if (isSvgTagNotDetected(str)) - return; - - if (str.value().contains("")) { - ctx.addIssue(str, DESCRIPTION); - } - } - - private boolean isSvgTagNotDetected(StringElement str) { - return !str.value().contains(""); - } -} diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java deleted file mode 100644 index a69599aed..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormat.java +++ /dev/null @@ -1,35 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.sonar.check.Rule; -import org.sonar.plugins.python.api.PythonSubscriptionCheck; -import org.sonar.plugins.python.api.SubscriptionContext; -import org.sonar.plugins.python.api.tree.StringLiteral; -import org.sonar.plugins.python.api.tree.Tree; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -@Rule(key = "EC203") -public class DetectUnoptimizedImageFormat extends PythonSubscriptionCheck { - - protected static final String RULE_KEY = "EC203"; - protected static final String MESSAGERULE = "Detect unoptimized image format"; - protected static final String MESSAGEERROR = "If possible, the utilisation of svg image format (or html tag) is recommended over other image format."; - protected static final Pattern IMGEXTENSION = Pattern.compile("\\.(bmp|ico|tiff|webp|png|jpg|jpeg|jfif|pjpeg|pjp|gif|avif|apng)"); - - @Override - public void initialize(Context context) { - context.registerSyntaxNodeConsumer(Tree.Kind.STRING_LITERAL, this::visitNodeString); - } - - public void visitNodeString(SubscriptionContext ctx) { - if (ctx.syntaxNode().is(Tree.Kind.STRING_LITERAL)) { - final StringLiteral stringLiteral = (StringLiteral) ctx.syntaxNode(); - final String strValue = stringLiteral.trimmedQuotesValue(); - final Matcher matcher = IMGEXTENSION.matcher(strValue); - if(matcher.find()) { - ctx.addIssue(stringLiteral, MESSAGEERROR); - } - } - } -} diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoop.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoop.java deleted file mode 100644 index b0bf30286..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoop.java +++ /dev/null @@ -1,24 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.sonar.check.Rule; -import org.sonar.plugins.python.api.PythonSubscriptionCheck; -import org.sonar.plugins.python.api.tree.CallExpression; -import org.sonar.plugins.python.api.tree.Tree; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC69") -@DeprecatedRuleKey(repositoryKey = "gci-python", ruleKey = "S69") -public class NoFunctionCallWhenDeclaringForLoop extends PythonSubscriptionCheck { - - public static final String DESCRIPTION = "Do not call a function when declaring a for-type loop"; - - @Override - public void initialize(Context context) { - context.registerSyntaxNodeConsumer(Tree.Kind.CALL_EXPR, ctx -> { - CallExpression callExpression = (CallExpression) ctx.syntaxNode(); - if (callExpression.parent().getKind() == Tree.Kind.FOR_STMT) { - ctx.addIssue(callExpression, NoFunctionCallWhenDeclaringForLoop.DESCRIPTION); - } - }); - } -} diff --git a/python-plugin/src/main/java/fr/greencodeinitiative/python/package-info.java b/python-plugin/src/main/java/fr/greencodeinitiative/python/package-info.java deleted file mode 100644 index 51a7a570e..000000000 --- a/python-plugin/src/main/java/fr/greencodeinitiative/python/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (C) 2023 Green Code Initiative - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -@ParametersAreNonnullByDefault -package fr.greencodeinitiative.python; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java deleted file mode 100644 index e270ad449..000000000 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonPluginTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2023 Green Code Initiative - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.python; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.sonar.api.Plugin; -import org.sonar.api.SonarRuntime; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -class PythonPluginTest { - private Plugin.Context context; - - @BeforeEach - void init() { - SonarRuntime sonarRuntime = mock(SonarRuntime.class); - context = new Plugin.Context(sonarRuntime); - new PythonPlugin().define(context); - } - - @Test - void test() { - assertThat(context.getExtensions()).hasSize(1); - } - -} diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java deleted file mode 100644 index 714ef278e..000000000 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/PythonRuleRepositoryTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2023 Green Code Initiative - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.python; - -import org.assertj.core.api.SoftAssertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.sonar.api.SonarRuntime; -import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.api.utils.Version; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -class PythonRuleRepositoryTest { - - private RulesDefinition.Repository repository; - - @BeforeEach - void init() { - // TODO: Remove this check after Git repo split - /* - On an IDE (like IntelliJ), if the developer runs the unit tests without building/generating the Maven goals on the - "ecocode-rules-specifications" module before, the unit tests will not see the generated HTML descriptions (from ASCIIDOC files). - The developer must therefore configure his IDE to build the `ecocode-rules-specifications` module before launching the Tests. - - When the `python-plugin` submodule is in a specific Git repository, `ecocode-rules-specifications` will be fetched from a classic - external Maven dependency. There will therefore no longer be any need to perform this specific configuration. - */ - if (PythonRuleRepository.class.getResource("/io/ecocode/rules/python/EC4.json") == null) { - String message = "'ecocode-rules-specification' resources corrupted. Please check build of 'ecocode-rules-specification' module"; - if (System.getProperties().keySet().stream().anyMatch(k -> k.toString().startsWith("idea."))) { - message += "\n\nOn 'IntelliJ IDEA':" + - "\n1. go to settings :" + - "\n > Build, Execution, Deployment > Build Tools > Maven > Runner" + - "\n2. check option:" + - "\n > Delegate IDE build/run actions to Maven" + - "\n3. Click on menu: " + - "\n > Build > Build Project" - ; - } - fail(message); - } - - final SonarRuntime sonarRuntime = mock(SonarRuntime.class); - doReturn(Version.create(0, 0)).when(sonarRuntime).getApiVersion(); - PythonRuleRepository rulesDefinition = new PythonRuleRepository(sonarRuntime); - RulesDefinition.Context context = new RulesDefinition.Context(); - rulesDefinition.define(context); - repository = context.repository(rulesDefinition.repositoryKey()); - } - - @Test - @DisplayName("Test repository metadata") - void testMetadata() { - assertThat(repository.name()).isEqualTo("ecoCode"); - assertThat(repository.language()).isEqualTo("py"); - assertThat(repository.key()).isEqualTo("ecocode-python"); - } - - @Test - void testRegistredRules() { - assertThat(repository.rules()).hasSize(10); - } - - @Test - @DisplayName("All rule keys must be prefixed by 'EC'") - void testRuleKeyPrefix() { - SoftAssertions assertions = new SoftAssertions(); - repository.rules().forEach( - rule -> assertions.assertThat(rule.key()).startsWith("EC") - ); - assertions.assertAll(); - } - - @Test - void testAllRuleParametersHaveDescription() { - SoftAssertions assertions = new SoftAssertions(); - repository.rules().stream() - .flatMap(rule -> rule.params().stream()) - .forEach(param -> assertions.assertThat(param.description()) - .as("description for " + param.key()) - .isNotEmpty()); - assertions.assertAll(); - } -} diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteTest.java deleted file mode 100644 index 1079b1050..000000000 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidDoubleQuoteTest.java +++ /dev/null @@ -1,11 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.junit.Test; -import org.sonar.python.checks.utils.PythonCheckVerifier; - -public class AvoidDoubleQuoteTest { - @Test - public void test() { - PythonCheckVerifier.verify("src/test/resources/checks/avoidDoubleQuoteCheck.py", new AvoidDoubleQuoteCheck()); - } -} diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequestTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequestTest.java deleted file mode 100644 index e03a71fa2..000000000 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidFullSQLRequestTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.junit.Test; -import org.sonar.python.checks.utils.PythonCheckVerifier; - -public class AvoidFullSQLRequestTest { - - @Test - public void test() { - PythonCheckVerifier.verify("src/test/resources/checks/avoidFullSQLRequest.py", new AvoidFullSQLRequest()); - } -} diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSettersTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSettersTest.java deleted file mode 100644 index 26d7b4db3..000000000 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidGettersAndSettersTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.junit.Test; -import org.sonar.python.checks.utils.PythonCheckVerifier; - -public class AvoidGettersAndSettersTest { - - @Test - public void test() { - PythonCheckVerifier.verify("src/test/resources/checks/avoidGettersAndSetters.py", new AvoidGettersAndSetters()); - } -} diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheckTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheckTest.java deleted file mode 100644 index c58ed4bc8..000000000 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidGlobalVariableInFunctionCheckTest.java +++ /dev/null @@ -1,11 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.junit.Test; -import org.sonar.python.checks.utils.PythonCheckVerifier; - -public class AvoidGlobalVariableInFunctionCheckTest { - @Test - public void test() { - PythonCheckVerifier.verify("src/test/resources/checks/avoidGlobalVariableInFunction.py", new AvoidGlobalVariableInFunctionCheck()); - } -} diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterationsTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterationsTest.java deleted file mode 100644 index 8e722c25b..000000000 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidListComprehensionInIterationsTest.java +++ /dev/null @@ -1,11 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.junit.Test; -import org.sonar.python.checks.utils.PythonCheckVerifier; - -public class AvoidListComprehensionInIterationsTest { - @Test - public void test() { - PythonCheckVerifier.verify("src/test/resources/checks/AvoidListComprehensionInIterations.py", new AvoidListComprehensionInIterations()); - } -} diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoopTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoopTest.java deleted file mode 100644 index a982bf0ef..000000000 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidSQLRequestInLoopTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.junit.Test; -import org.sonar.python.checks.utils.PythonCheckVerifier; - -public class AvoidSQLRequestInLoopTest { - @Test - public void test() { - PythonCheckVerifier.verify("src/test/resources/checks/avoidSQLRequestInLoop.py", new AvoidSQLRequestInLoop()); - PythonCheckVerifier.verifyNoIssue("src/test/resources/checks/avoidSQLRequestInLoopNoImports.py", new AvoidSQLRequestInLoop()); - } -} diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheckTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheckTest.java deleted file mode 100644 index 03450d068..000000000 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidTryCatchFinallyCheckTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package fr.greencodeinitiative.python.checks; - - -import org.junit.Test; -import org.sonar.python.checks.utils.PythonCheckVerifier; - -public class AvoidTryCatchFinallyCheckTest { - @Test - public void test() { - PythonCheckVerifier.verify("src/test/resources/checks/avoidTryCatchFinallyCheck.py", new AvoidTryCatchFinallyCheck()); - } -} diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesTest.java deleted file mode 100644 index 09a738575..000000000 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/AvoidUnoptimizedVectorImagesTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.junit.Test; -import org.sonar.python.checks.utils.PythonCheckVerifier; - -public class AvoidUnoptimizedVectorImagesTest { - - @Test - public void test() { - PythonCheckVerifier.verify("src/test/resources/checks/avoidUnoptimizedVectorImages.py", new AvoidUnoptimizedVectorImagesCheck()); - } -} diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java deleted file mode 100644 index 7c735f59f..000000000 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/DetectUnoptimizedImageFormatTest.java +++ /dev/null @@ -1,13 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.junit.Test; -import org.sonar.python.checks.utils.PythonCheckVerifier; - -public class DetectUnoptimizedImageFormatTest { - - @Test - public void test() { - PythonCheckVerifier.verify("src/test/resources/checks/detectUnoptimizedImageFormat.py", new DetectUnoptimizedImageFormat()); - PythonCheckVerifier.verifyNoIssue("src/test/resources/checks/detectUnoptimizedImageFormatCompliant.py", new DetectUnoptimizedImageFormat()); - } -} diff --git a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoopTest.java b/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoopTest.java deleted file mode 100644 index 77b1feb31..000000000 --- a/python-plugin/src/test/java/fr/greencodeinitiative/python/checks/NoFunctionCallWhenDeclaringForLoopTest.java +++ /dev/null @@ -1,11 +0,0 @@ -package fr.greencodeinitiative.python.checks; - -import org.junit.Test; -import org.sonar.python.checks.utils.PythonCheckVerifier; - -public class NoFunctionCallWhenDeclaringForLoopTest { - @Test - public void test() { - PythonCheckVerifier.verify("src/test/resources/checks/noFunctionCallWhenDeclaringForLoop.py", new NoFunctionCallWhenDeclaringForLoop()); - } -} diff --git a/python-plugin/src/test/resources/checks/AvoidListComprehensionInIterations.py b/python-plugin/src/test/resources/checks/AvoidListComprehensionInIterations.py deleted file mode 100644 index 547eb5724..000000000 --- a/python-plugin/src/test/resources/checks/AvoidListComprehensionInIterations.py +++ /dev/null @@ -1,35 +0,0 @@ -def non_compliant_example_basic(): - for var in [var2 for var2 in range(1000)]: # Noncompliant {{Use generator comprehension instead of list comprehension in for loop declaration}} - print(var) - -def non_compliant_example_enumerate(): - for idx, var in enumerate([var2 for var2 in range(1000)]): # Noncompliant {{Use generator comprehension instead of list comprehension in for loop declaration}} - print(var) - -def non_compliant_example_zip(): - for var, var_ in zip([var2 for var2 in range(1000)], [var2 for var2 in range(1000)]): # Noncompliant {{Use generator comprehension instead of list comprehension in for loop declaration}} {{Use generator comprehension instead of list comprehension in for loop declaration}} - print(var) - -def non_compliant_example_enumerate_zip(): - for packed_var in enumerate(zip([1, 2, 3], filter(bool, [idx % 2 for idx in range(100)]))): # Noncompliant {{Use generator comprehension instead of list comprehension in for loop declaration}} - print(packed_var) - -def compliant_example_basic_1(): - for var in range(10): - print(var) - -def compliant_example_basic_2(): - for var in (var2 for var2 in range(1000)): - print(var) - -def compliant_example_with_filter(): - for var in filter(lambda x: x > 2, range(100)): - print(var) - -def compliant_example_with_enumerate(): - for idx, var in enumerate(range(1000)): - print(var) - -def compliant_example_with_zip(): - for var, var2 in zip((idx for idx in range(3)), ["a", "b", "c"]): - print(var) diff --git a/python-plugin/src/test/resources/checks/avoidDoubleQuoteCheck.py b/python-plugin/src/test/resources/checks/avoidDoubleQuoteCheck.py deleted file mode 100644 index 893f24e8e..000000000 --- a/python-plugin/src/test/resources/checks/avoidDoubleQuoteCheck.py +++ /dev/null @@ -1,13 +0,0 @@ -# in variables -firstname = "Andrea" # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}} -lastname = 'Doe' -cars = ["Renault", "Fiat", "Citroen"] # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}} {{Avoid using quotation mark ("), prefer using simple quote (')}} {{Avoid using quotation mark ("), prefer using simple quote (')}} -courses = ['mathematics', 'french', 'IT sciences'] -instruments = ['guitar', "bass", 'drums'] # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}} - -# in functions -def my_function(name, age): - print(name + 'is' + age + ' yo.') - -my_function("Robert", 12) # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}} -my_function('Robert', 12) diff --git a/python-plugin/src/test/resources/checks/avoidFullSQLRequest.py b/python-plugin/src/test/resources/checks/avoidFullSQLRequest.py deleted file mode 100644 index 66c6adb4c..000000000 --- a/python-plugin/src/test/resources/checks/avoidFullSQLRequest.py +++ /dev/null @@ -1,10 +0,0 @@ -def displayMessage(argument1): - print(argument) - -displayMessage(' sElEcT * fRoM myTable') # Noncompliant {{Don't use the query SELECT * FROM}} -displayMessage(' sElEcT user fRoM myTable') - -requestNonCompiliant = ' SeLeCt * FrOm myTable' # Noncompliant {{Don't use the query SELECT * FROM}} -requestCompiliant = ' SeLeCt user FrOm myTable' -displayMessage(requestNonCompiliant) -displayMessage(requestCompiliant) diff --git a/python-plugin/src/test/resources/checks/avoidGettersAndSetters.py b/python-plugin/src/test/resources/checks/avoidGettersAndSetters.py deleted file mode 100644 index 538e79a79..000000000 --- a/python-plugin/src/test/resources/checks/avoidGettersAndSetters.py +++ /dev/null @@ -1,26 +0,0 @@ -from datetime import date - -class Client(): - - def __init__(self, age, weight): - self.age = age - self.weight = weight - - def set_age(self, age): # Noncompliant {{Avoid creating getter and setter methods in classes}} - self.age = age - - def set_age(self, age2): # Noncompliant {{Avoid creating getter and setter methods in classes}} - self.age = age2 - - def get_age_in_five_years(self): - a = Client() - return a.age - - def get_age(self): # Noncompliant {{Avoid creating getter and setter methods in classes}} - return self.age - - def is_major(self): - return self.age >= 18 - - def get_weight(self): # Noncompliant {{Avoid creating getter and setter methods in classes}} - return self.weight diff --git a/python-plugin/src/test/resources/checks/avoidGlobalVariableInFunction.py b/python-plugin/src/test/resources/checks/avoidGlobalVariableInFunction.py deleted file mode 100644 index 9b77dfa72..000000000 --- a/python-plugin/src/test/resources/checks/avoidGlobalVariableInFunction.py +++ /dev/null @@ -1,43 +0,0 @@ -global_var = 'global' - -def print_global_var_details(): - print(len(global_var)) # Noncompliant - print('Global var : ', global_var) # Noncompliant - print('Global var : ' + global_var) # Noncompliant - for c in global_var: # Noncompliant - print(c) - if len(global_var) > 0: # Noncompliant - print('global_var len positive') - elif 0 < len(global_var): # Noncompliant - print('global_var len negative') - else: - print('global_var len = 0') - - try: - print(global_var) # Noncompliant - except: - print(global_var) # Noncompliant - else: - print(global_var) # Noncompliant - finally: - print(global_var) # Noncompliant - - assert len(global_var) > 0, 'Failed' # Noncompliant - assert len('test') > 0, 'Failed : ' + global_var # Noncompliant - test = '' - test += global_var # Noncompliant - test = {'test': global_var, 'global_var': 1 } # Noncompliant - -# Compliant -def print_var_length(local_var = global_var): - global_var = 'local' # Here it create a local var and do not use the global var - global_var: str = 'local' # Here it create a local var and do not use the global var - global_var += 'local' # Here it create a local var and do not use the global var - global_var = 'local' if True else 'global' # Here it create a local var and do not use the global var - print(len(global_var)) # Compliant for the use, but not for the name of the var - print(len(local_var)) - for global_var in local_var: # Compliant but not for the name - print(global_var) - -print_global_var_details() -print_var_length(global_var) diff --git a/python-plugin/src/test/resources/checks/avoidSQLRequestInLoop.py b/python-plugin/src/test/resources/checks/avoidSQLRequestInLoop.py deleted file mode 100644 index 394088199..000000000 --- a/python-plugin/src/test/resources/checks/avoidSQLRequestInLoop.py +++ /dev/null @@ -1,42 +0,0 @@ -import mysql.connector -import psycopg2 -import pyodbc -import sqlite3 - -def mysql_loop(): - connection = mysql.connector.connect(database='local') - cursor = connection.cursor() - results = [] - for id in range(5): - results.append(cursor.execute("SELECT name FROM user WHERE id = ?", (id)).fetchone()) # Noncompliant {{Avoid performing SQL queries within a loop}} - connection.close() - return results - -def psycopg2_loop(): - connection = psycopg2.connect(database='local') - cursor = connection.cursor() - results = [] - id = 0 - while id <= 5: - results.append(cursor.execute("SELECT name FROM user WHERE id = ?", (id)).fetchone()) # Noncompliant {{Avoid performing SQL queries within a loop}} - id += 1 - connection.close() - return results - -def pyodbc_loop(): - connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE=local') - cursor = connection.cursor() - results = [] - for id in range(5): - results.append(cursor.execute("SELECT name FROM user WHERE id = ?", (id)).fetchone()) # Noncompliant {{Avoid performing SQL queries within a loop}} - connection.close() - return results - -def sqlite3_loop(): - connection = sqlite3.connect("local.db") - cursor = connection.cursor() - results = [] - for id in range(5): - results.append(cursor.execute("SELECT name FROM user WHERE id = ?", (id)).fetchone()) # Noncompliant {{Avoid performing SQL queries within a loop}} - connection.close() - return results diff --git a/python-plugin/src/test/resources/checks/avoidSQLRequestInLoopCheck.py b/python-plugin/src/test/resources/checks/avoidSQLRequestInLoopCheck.py deleted file mode 100644 index 7f98cd548..000000000 --- a/python-plugin/src/test/resources/checks/avoidSQLRequestInLoopCheck.py +++ /dev/null @@ -1,83 +0,0 @@ -import mysql.connector - - -class AvoidSQLRequestInLoopCheck: - maxrows = 20 - - def testWithNoLoop(self): - try : - db = mysql.connector.connect(option_files='my.conf', use_pure=True) - cursor = db.cursor(dictionary=True) - - cursor.execute('SELECT id, name FROM users LIMIT %(limit)s', {'limit': self.maxrows}) - for row in cursor.fetchall(): - print("{}: {}".format(row['id'], row['name'])) - - cursor.close() - db.close() - except mysql.connector.Error as err: - print("Got an exception: {}".format(err)) - db.close() - - def testWithForLoop(self): - try: - db = mysql.connector.connect(option_files='my.conf', use_pure=True) - cursor = db.cursor(dictionary=True) - - for i in range(0, self.maxrows): - cursor.execute("SELECT id, name FROM users WHERE id = %(id)s", {'id': i+1}) #Noncompliant - for row in cursor.fetchall(): - print("{}: {}".format(row['id'], row['name'])) - - cursor.close() - db.close() - except mysql.connector.Error as err: - print("Got an exception: {}".format(err)) - db.close() - - def testWithWhileLoop(self): - try: - db = mysql.connector.connect(option_files='my.conf', use_pure=True) - cursor = db.cursor(dictionary=True) - - i = 0 - while i < self.maxrows: - cursor.execute("SELECT id, name FROM users WHERE id = %(id)s", {'id': i+1}) #Noncompliant - for row in cursor.fetchall(): - print("name: {}".format(row['name'])) - i += 1 - - cursor.close() - db.close() - except mysql.connector.Error as err: - print("Got an exception: {}".format(err)) - db.close() - - def testWithWhileLoopUpdate(self): - try: - db = mysql.connector.connect(option_files='my.conf', use_pure=True) - cursor=db.cursor() - - i = 0 - while i < self.maxrows: - cursor.execute('UPDATE users set name=%(name)s where id=%(id)s', {'name': "anonymous", 'id': i+1}) - i+=1 - db.commit() - - cursor.close() - db.close() - except mysql.connector.Error as err: - print("Got an exception: {}".format(err)) - db.close() - -if __name__ == '__main__': - test = AvoidSQLRequestInLoopCheck() - - print("testWithNoLoop") - test.testWithNoLoop() - print("testWithForLoop") - test.testWithForLoop() - print("testWithWhileLoop") - test.testWithWhileLoop() - print("testWithWhileLoopUpdate") - test.testWithWhileLoopUpdate() diff --git a/python-plugin/src/test/resources/checks/avoidSQLRequestInLoopNoImports.py b/python-plugin/src/test/resources/checks/avoidSQLRequestInLoopNoImports.py deleted file mode 100644 index fe8513844..000000000 --- a/python-plugin/src/test/resources/checks/avoidSQLRequestInLoopNoImports.py +++ /dev/null @@ -1,26 +0,0 @@ -def mysql_loop(): - connection = mysql.connector.connect(database='local') - cursor = connection.cursor() - results = [] - for id in range(5): - results.append(cursor.execute("SELECT name FROM user WHERE id = ?", (id)).fetchone()) # OK - connection.close() - return results - -def pyodbc_loop(): - connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE=local') - cursor = connection.cursor() - results = [] - for id in range(5): - results.append(cursor.execute("SELECT name FROM user WHERE id = ?", (id)).fetchone()) # OK - connection.close() - return results - -def sqlite3_loop(): - connection = sqlite3.connect("local.db") - cursor = connection.cursor() - results = [] - for id in range(5): - results.append(cursor.execute("SELECT name FROM user WHERE id = ?", (id)).fetchone()) # OK - connection.close() - return results diff --git a/python-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck.py b/python-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck.py deleted file mode 100644 index cbd081e0e..000000000 --- a/python-plugin/src/test/resources/checks/avoidTryCatchFinallyCheck.py +++ /dev/null @@ -1,29 +0,0 @@ -import os.path - -path = 'hello.txt' - - -def my_function(): - x=0 - - try: # Noncompliant {{Avoid the use of try-catch}} - print(x) - except: - print("Something went wrong") - finally: - print("The 'try except' is finished") - -def foo(): - try: # Noncompliant {{Avoid the use of try-catch}} - f = open(path) - print(f.read()) - except: - print('No such file '+path) - finally: - f.close() - -def boo(): - if os.path.isfile(path): - fh = open(path, 'r') - print(fh.read()) - fh.close diff --git a/python-plugin/src/test/resources/checks/avoidUnoptimizedVectorImages.py b/python-plugin/src/test/resources/checks/avoidUnoptimizedVectorImages.py deleted file mode 100644 index 9893da59c..000000000 --- a/python-plugin/src/test/resources/checks/avoidUnoptimizedVectorImages.py +++ /dev/null @@ -1,5 +0,0 @@ -image0 = """""" -image1 = """""" # Noncompliant {{Avoid using unoptimized vector images}} -image2 = "" # Noncompliant {{Avoid using unoptimized vector images}} -image3 = "......" # Noncompliant {{Avoid using unoptimized vector images}} -image4 = "" # Noncompliant {{Avoid using unoptimized vector images}} diff --git a/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormat.py b/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormat.py deleted file mode 100644 index 37ddac218..000000000 --- a/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormat.py +++ /dev/null @@ -1,36 +0,0 @@ - -def testImage(image) : - return "path/to/" + image - - -def testImageFormat2() : - - img_bmp = "test/image.bmp" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - img_ico = "image.ico" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - img_tiff = "test/path/to/image.tiff" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - img_webp = "test/path/to/" + "image.webp" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - img_jpg = "image.jpg" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - img_jpeg = "image.jpeg" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - img_jfif = "image.jfif" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - img_pjpeg = "image.pjpeg" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - img_pjp = "image.pjp" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - img_gif = "image.gif" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - img_avif = "image.avif" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - img_apng = "image.apng" # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - - image_format = testImage("image.jpg") # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - - return ('' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' # Noncompliant {{If possible, the utilisation of svg image format (or html tag) is recommended over other image format.}} - + '' ) diff --git a/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatCompliant.py b/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatCompliant.py deleted file mode 100644 index 205f125e7..000000000 --- a/python-plugin/src/test/resources/checks/detectUnoptimizedImageFormatCompliant.py +++ /dev/null @@ -1,17 +0,0 @@ - -def testImage(image) : - return "path/to/" + image - - -def testImageFormat2() : - - img_svg = "test/image.svg" # Compliant - - image_format = testImage("image.svg") # Compliant - - image_svg_html = ('' + # Compliant - '' + - '') - - return ('' # Compliant - + '' ) diff --git a/python-plugin/src/test/resources/checks/init_dbtest.sql b/python-plugin/src/test/resources/checks/init_dbtest.sql deleted file mode 100644 index 9a7a0a524..000000000 --- a/python-plugin/src/test/resources/checks/init_dbtest.sql +++ /dev/null @@ -1,34 +0,0 @@ -DROP TABLE IF EXISTS users; - -CREATE TABLE users ( - id INT NOT NULL AUTO_INCREMENT, - name VARCHAR(255), - PRIMARY KEY (id) -); - -INSERT INTO users(name) VALUES('a'); -INSERT INTO users(name) VALUES('b'); -INSERT INTO users(name) VALUES('c'); -INSERT INTO users(name) VALUES('d'); -INSERT INTO users(name) VALUES('e'); -INSERT INTO users(name) VALUES('f'); -INSERT INTO users(name) VALUES('g'); -INSERT INTO users(name) VALUES('h'); -INSERT INTO users(name) VALUES('i'); -INSERT INTO users(name) VALUES('j'); -INSERT INTO users(name) VALUES('k'); -INSERT INTO users(name) VALUES('l'); -INSERT INTO users(name) VALUES('m'); -INSERT INTO users(name) VALUES('n'); -INSERT INTO users(name) VALUES('o'); -INSERT INTO users(name) VALUES('p'); -INSERT INTO users(name) VALUES('q'); -INSERT INTO users(name) VALUES('r'); -INSERT INTO users(name) VALUES('s'); -INSERT INTO users(name) VALUES('t'); -INSERT INTO users(name) VALUES('u'); -INSERT INTO users(name) VALUES('v'); -INSERT INTO users(name) VALUES('w'); -INSERT INTO users(name) VALUES('x'); -INSERT INTO users(name) VALUES('y'); -INSERT INTO users(name) VALUES('z'); diff --git a/python-plugin/src/test/resources/checks/my.conf.sample b/python-plugin/src/test/resources/checks/my.conf.sample deleted file mode 100644 index e10dc23bc..000000000 --- a/python-plugin/src/test/resources/checks/my.conf.sample +++ /dev/null @@ -1,5 +0,0 @@ -[client] -host = localhost -user = dbtest -password = dbtest -database = dbtest diff --git a/python-plugin/src/test/resources/checks/noFunctionCallWhenDeclaringForLoop.py b/python-plugin/src/test/resources/checks/noFunctionCallWhenDeclaringForLoop.py deleted file mode 100644 index 97cb01e63..000000000 --- a/python-plugin/src/test/resources/checks/noFunctionCallWhenDeclaringForLoop.py +++ /dev/null @@ -1,9 +0,0 @@ -def my_function(): - return 6 - -for i in my_function(): # Noncompliant {{Do not call a function when declaring a for-type loop}} - print("Test") - my_function() - pass - -my_function() From c1b8d30cef81d684e75162c0e732e6450f1e0b54 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 8 Aug 2023 19:10:14 +0200 Subject: [PATCH 150/170] [ISSUE 182] upgrade INSTALL.md --- INSTALL.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/INSTALL.md b/INSTALL.md index e4e1395cc..f9fabdb89 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -1,18 +1,19 @@ -- [Project structure](#project-structure) -- [Plugin-specific guides](#plugin-specific-guides) +# Install notes -Common installation notes / requirements -======================================== +- [Common installation notes / requirements](#common-installation-notes--requirements) +- [Special points for Standard plugins](#special-points-for-standard-plugins) + - [Project structure](#project-structure) + - [Plugin-specific guides](#plugin-specific-guides) + +## Common installation notes / requirements Please read common [INSTALL.md](https://github.com/green-code-initiative/ecoCode-common/blob/main/doc/INSTALL.md) in `ecoCode-common` repository. Please follow the specific guides below for additional information on installing the desired plugins. -Special points for Standard plugins -================================= +## Special points for Standard plugins -Project structure ------------------ +### Project structure Here is a preview of project tree : @@ -28,8 +29,7 @@ ecoCode # Root directory You will find more information about the plugins’ architecture in their folders -Plugin-specific guides ----------------------- +### Plugin-specific guides - [Java how-to](java-plugin/README.md) - [PHP how-to](php-plugin/README.md) From 3d3a9595d823240c709865c211176bada9dc7b8d Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 8 Aug 2023 19:39:17 +0200 Subject: [PATCH 151/170] [ISSUE 182] PHP - remove PHP module because of moving to new repository --- .github/workflows/manual_release.yml | 21 - .github/workflows/tag_release.yml | 21 - CHANGELOG.md | 1 + INSTALL.md | 3 - TODOs_DDC.md | 2 - docker-compose.yml | 7 +- ecocode-rules-specifications/pom.xml | 2 +- java-plugin/pom.xml | 2 +- php-plugin/README.md | 1 - php-plugin/pom.xml | 143 ------ .../fr/greencodeinitiative/php/PHPPlugin.java | 28 -- .../php/PhpRuleRepository.java | 69 --- .../php/checks/AvoidDoubleQuoteCheck.java | 65 --- .../php/checks/AvoidFullSQLRequestCheck.java | 35 -- ...AvoidGettingSizeCollectionInLoopCheck.java | 63 --- .../AvoidMultipleIfElseStatementCheck.java | 386 --------------- .../checks/AvoidSQLRequestInLoopCheck.java | 82 ---- ...inallyCheck_NOK_failsAllTryStatements.java | 27 -- .../AvoidUsingGlobalVariablesCheck.java | 24 - .../php/checks/IncrementCheck.java | 28 -- .../NoFunctionCallWhenDeclaringForLoop.java | 51 -- .../UseOfMethodsForBasicOperations.java | 93 ---- .../php/PhpPluginTest.java | 42 -- .../php/PhpRuleRepositoryTest.java | 103 ---- .../php/checks/AvoidDoubleQuoteCheckTest.java | 16 - .../checks/AvoidFullSQLRequestCheckTest.java | 15 - .../AvoidGettingSizeCollectionInLoopTest.java | 15 - ...AvoidMultipleIfElseStatementCheckTest.java | 38 -- .../AvoidSQLRequestInLoopCheckTest.java | 15 - ...allyCheckNOKfailsAllTryStatementsTest.java | 16 - .../AvoidUsingGlobalVariablesCheckTest.java | 16 - .../php/checks/IncrementCheckTest.java | 16 - ...oFunctionCallWhenDeclaringForLoopTest.java | 15 - .../UseOfMethodsForBasicOperationsTest.java | 15 - .../resources/checks/AvoidDoubleQuote.php | 24 - .../resources/checks/AvoidFullSQLRequest.php | 25 - .../AvoidGettingSizeCollectionInLoop.php | 231 --------- .../checks/AvoidMultipleIfElseStatement.php | 453 ------------------ .../checks/AvoidSQLRequestInLoop.php | 80 ---- ...FinallyCheck_NOK_FailsAllTryStatements.php | 37 -- .../checks/AvoidUsingGlobalVariablesCheck.php | 28 -- .../test/resources/checks/IncrementCheck.php | 13 - .../NoFunctionCallWhenDeclaringForLoop.php | 47 -- .../checks/UseOfMethodsForBasicOperations.php | 18 - pom.xml | 13 +- 45 files changed, 6 insertions(+), 2439 deletions(-) delete mode 100644 php-plugin/README.md delete mode 100644 php-plugin/pom.xml delete mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/PHPPlugin.java delete mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java delete mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheck.java delete mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheck.java delete mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopCheck.java delete mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java delete mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheck.java delete mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.java delete mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheck.java delete mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java delete mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoop.java delete mode 100644 php-plugin/src/main/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperations.java delete mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java delete mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java delete mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheckTest.java delete mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheckTest.java delete mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopTest.java delete mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheckTest.java delete mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheckTest.java delete mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheckNOKfailsAllTryStatementsTest.java delete mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheckTest.java delete mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/checks/IncrementCheckTest.java delete mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoopTest.java delete mode 100644 php-plugin/src/test/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperationsTest.java delete mode 100644 php-plugin/src/test/resources/checks/AvoidDoubleQuote.php delete mode 100644 php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php delete mode 100644 php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInLoop.php delete mode 100644 php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php delete mode 100644 php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php delete mode 100644 php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php delete mode 100644 php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php delete mode 100644 php-plugin/src/test/resources/checks/IncrementCheck.php delete mode 100644 php-plugin/src/test/resources/checks/NoFunctionCallWhenDeclaringForLoop.php delete mode 100644 php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php diff --git a/.github/workflows/manual_release.yml b/.github/workflows/manual_release.yml index 5b9292792..90818a555 100644 --- a/.github/workflows/manual_release.yml +++ b/.github/workflows/manual_release.yml @@ -89,24 +89,3 @@ jobs: asset_path: lib/ecocode-java-plugin-${{ needs.build.outputs.last_tag }}.jar asset_name: ecocode-java-plugin-${{ needs.build.outputs.last_tag }}.jar asset_content_type: application/zip - upload-php: - name: Upload PHP Plugin - runs-on: ubuntu-latest - needs: build - steps: - - name: Import plugin JAR files - id: import_jar_files - uses: actions/download-artifact@v3 - with: - name: ecocode-plugins - path: lib - - name: Upload Release Asset - PHP Plugin - id: upload-release-asset - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{needs.build.outputs.upload_url}} - asset_path: lib/ecocode-php-plugin-${{ needs.build.outputs.last_tag }}.jar - asset_name: ecocode-php-plugin-${{ needs.build.outputs.last_tag }}.jar - asset_content_type: application/zip diff --git a/.github/workflows/tag_release.yml b/.github/workflows/tag_release.yml index c71d22ed9..44ec92a15 100644 --- a/.github/workflows/tag_release.yml +++ b/.github/workflows/tag_release.yml @@ -69,24 +69,3 @@ jobs: asset_path: lib/ecocode-java-plugin-${{ github.ref_name }}.jar asset_name: ecocode-java-plugin-${{ github.ref_name }}.jar asset_content_type: application/zip - upload-php: - name: Upload PHP Plugin - runs-on: ubuntu-latest - needs: build - steps: - - name: Import plugin JAR files - id: import_jar_files - uses: actions/download-artifact@v3 - with: - name: ecocode-plugins - path: lib - - name: Upload Release Asset - PHP Plugin - id: upload-release-asset - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{needs.build.outputs.upload_url}} - asset_path: lib/ecocode-php-plugin-${{ github.ref_name }}.jar - asset_name: ecocode-php-plugin-${{ github.ref_name }}.jar - asset_content_type: application/zip diff --git a/CHANGELOG.md b/CHANGELOG.md index 2856e6d93..8a5dd33f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Deleted - [#182](https://github.com/green-code-initiative/ecoCode/issues/182) Split repository : move Python module to new `ecoCode-python` repository +- [#182](https://github.com/green-code-initiative/ecoCode/issues/182) Split repository : move Php module to new `ecoCode-php` repository ## [1.3.1] - 2023-07-19 diff --git a/INSTALL.md b/INSTALL.md index f9fabdb89..d459adc72 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -22,8 +22,6 @@ ecoCode # Root directory | +--java-plugin # JAVA | -+--php-plugin # PHP -| \--docker-compose.yml # Docker compose file ``` @@ -32,4 +30,3 @@ You will find more information about the plugins’ architecture in their folder ### Plugin-specific guides - [Java how-to](java-plugin/README.md) -- [PHP how-to](php-plugin/README.md) diff --git a/TODOs_DDC.md b/TODOs_DDC.md index 43c7dc222..712180f52 100644 --- a/TODOs_DDC.md +++ b/TODOs_DDC.md @@ -11,8 +11,6 @@ actions vues perso : - nettoyer le MIGRATION_TODOs.md - ménage dans les branches de dev (local et remote) - JYC : suppression dépendance analyser-commons ==> check si bien tout nettoyé (version dans pom, référence dans code) -- créer issue sur la rule EC2 (`avoidMultipleIfElse`) sur JAVA : - - JAVA : existe depuis longtemps !!! normal que l'implem PHP et python aient le même code minimaliste fonctionellement - voir les rules désativées chez PJ, créer des issues et corriger (`avoidMultipleIfElse`) : - voir pourquoi désactivées car ralaient trop - retester le EC2 \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 9240b111a..fb4d7bdda 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,11 +16,8 @@ services: SONAR_ES_BOOTSTRAP_CHECKS_DISABLE: 'true' volumes: - type: bind - source: ./java-plugin/target/ecocode-java-plugin-1.3.2-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.3.2-SNAPSHOT.jar - - type: bind - source: ./php-plugin/target/ecocode-php-plugin-1.3.2-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-php-plugin-1.3.2-SNAPSHOT.jar + source: ./java-plugin/target/ecocode-java-plugin-1.4.0-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.4.0-SNAPSHOT.jar - "extensions:/opt/sonarqube/extensions" - "logs:/opt/sonarqube/logs" - "data:/opt/sonarqube/data" diff --git a/ecocode-rules-specifications/pom.xml b/ecocode-rules-specifications/pom.xml index dd87cf7ca..ae208fe29 100644 --- a/ecocode-rules-specifications/pom.xml +++ b/ecocode-rules-specifications/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.2-SNAPSHOT + 1.4.0-SNAPSHOT ecocode-rules-specifications diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index 3e3741972..1bbc76ddb 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.3.2-SNAPSHOT + 1.4.0-SNAPSHOT ecocode-java-plugin diff --git a/php-plugin/README.md b/php-plugin/README.md deleted file mode 100644 index d7c7e9847..000000000 --- a/php-plugin/README.md +++ /dev/null @@ -1 +0,0 @@ -https://github.com/SonarSource/sonar-custom-rules-examples/tree/master/php-custom-rules \ No newline at end of file diff --git a/php-plugin/pom.xml b/php-plugin/pom.xml deleted file mode 100644 index db8b47669..000000000 --- a/php-plugin/pom.xml +++ /dev/null @@ -1,143 +0,0 @@ - - - 4.0.0 - - - io.ecocode - ecocode-parent - 1.3.2-SNAPSHOT - - - ecocode-php-plugin - sonar-plugin - - ecoCode - PHP language - Provides rules to reduce the environmental footprint of your PHP programs - https://github.com/green-code-initiative/ecoCode/tree/main/php-plugin - - - - ${project.groupId} - ecocode-rules-specifications - ${project.version} - php - - - - org.sonarsource.php - sonar-php-plugin - sonar-plugin - provided - - - - org.sonarsource.sonarqube - sonar-plugin-api - provided - - - - - - - - - - - - org.sonarsource.java - java-checks-testkit - test - - - - org.junit.jupiter - junit-jupiter - test - - - - org.assertj - assertj-core - test - - - - org.mockito - mockito-junit-jupiter - test - - - - - - - - org.sonarsource.sonar-packaging-maven-plugin - sonar-packaging-maven-plugin - true - - ecocodephp - ${project.name} - fr.greencodeinitiative.php.PHPPlugin - true - ${sonarqube.version} - ${java.version} - - - - - org.apache.maven.plugins - maven-shade-plugin - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-bundle - package - - copy - - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - jar - true - - - ../lib - - - - - - org.jacoco - jacoco-maven-plugin - - file - false - - - - prepare-agent - - prepare-agent - - - - report - test - - report - - - - - - - diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/PHPPlugin.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/PHPPlugin.java deleted file mode 100644 index 1a7afec6e..000000000 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/PHPPlugin.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2023 Green Code Initiative - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.php; - -import org.sonar.api.Plugin; - -public class PHPPlugin implements Plugin { - - @Override - public void define(Context context) { - context.addExtension(PhpRuleRepository.class); - } - -} diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java deleted file mode 100644 index 51a82b409..000000000 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/PhpRuleRepository.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2023 Green Code Initiative - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.php; - -import java.util.List; - -import fr.greencodeinitiative.php.checks.AvoidGettingSizeCollectionInLoopCheck; -import fr.greencodeinitiative.php.checks.*; -import org.sonar.api.SonarRuntime; -import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.plugins.php.api.visitors.PHPCustomRuleRepository; -import org.sonarsource.analyzer.commons.RuleMetadataLoader; - -public class PhpRuleRepository implements RulesDefinition, PHPCustomRuleRepository { - - private static final String LANGUAGE = "php"; - private static final String NAME = "ecoCode"; - private static final String RESOURCE_BASE_PATH = "io/ecocode/rules/php"; - private static final String REPOSITORY_KEY = "ecocode-php"; - - private final SonarRuntime sonarRuntime; - - public PhpRuleRepository(SonarRuntime sonarRuntime) { - this.sonarRuntime = sonarRuntime; - } - - @Override - public void define(Context context) { - NewRepository repository = context.createRepository(REPOSITORY_KEY, LANGUAGE).setName(NAME); - RuleMetadataLoader ruleMetadataLoader = new RuleMetadataLoader(RESOURCE_BASE_PATH, sonarRuntime); - ruleMetadataLoader.addRulesByAnnotatedClass(repository, checkClasses()); - repository.done(); - } - - @Override - public String repositoryKey() { - return REPOSITORY_KEY; - } - - @Override - public List> checkClasses() { - return List.of( - AvoidGettingSizeCollectionInLoopCheck.class, - AvoidDoubleQuoteCheck.class, - AvoidFullSQLRequestCheck.class, - AvoidSQLRequestInLoopCheck.class, - AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.class, - AvoidUsingGlobalVariablesCheck.class, - IncrementCheck.class, - NoFunctionCallWhenDeclaringForLoop.class, - UseOfMethodsForBasicOperations.class, - AvoidMultipleIfElseStatementCheck.class - ); - } -} diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheck.java deleted file mode 100644 index 67e6a7c47..000000000 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheck.java +++ /dev/null @@ -1,65 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.sonar.check.Rule; -import org.sonar.plugins.php.api.tree.Tree; -import org.sonar.plugins.php.api.tree.expression.LiteralTree; -import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC66") -@DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S66") -public class AvoidDoubleQuoteCheck extends PHPSubscriptionCheck { - - public static final String ERROR_MESSAGE = "Avoid using double quote (\"), prefer using simple quote (')"; - private static final Map> linesWithIssuesByFile = new HashMap<>(); - - @Override - public List nodesToVisit() { - return Collections.singletonList(Tree.Kind.REGULAR_STRING_LITERAL); - } - - @Override - public void visitNode(Tree tree) { - LiteralTree method = (LiteralTree) tree; - checkIssue(method); - } - - public void checkIssue(LiteralTree literalTree) { - if (lineAlreadyHasThisIssue(literalTree)) return; - if (literalTree.value().indexOf("\"") == 0 && literalTree.value().lastIndexOf("\"") == literalTree.value().length() - 1) { - repport(literalTree); - } - } - - private void repport(LiteralTree literalTree) { - if (literalTree.token() != null) { - - final String classname = context().getPhpFile().toString(); - final int line = literalTree.token().line(); - linesWithIssuesByFile.computeIfAbsent(classname, k -> new ArrayList<>()); - linesWithIssuesByFile.get(classname).add(line); - } - context().newIssue(this, literalTree, ERROR_MESSAGE); - - } - - private boolean lineAlreadyHasThisIssue(LiteralTree literalTree) { - if (literalTree.token() != null) { - final String filename = context().getPhpFile().toString(); - final int line = literalTree.token().line(); - - return linesWithIssuesByFile.containsKey(filename) - && linesWithIssuesByFile.get(filename).contains(line); - } - - return false; - } - -} diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheck.java deleted file mode 100644 index 61c175d36..000000000 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheck.java +++ /dev/null @@ -1,35 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.util.Arrays; -import java.util.List; -import java.util.regex.Pattern; - -import org.sonar.check.Rule; -import org.sonar.plugins.php.api.tree.Tree; -import org.sonar.plugins.php.api.tree.Tree.Kind; -import org.sonar.plugins.php.api.tree.expression.LiteralTree; -import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC74") -@DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S74") -public class AvoidFullSQLRequestCheck extends PHPSubscriptionCheck { - - public static final String ERROR_MESSAGE = "Don't use the query SELECT * FROM"; - - private static final Pattern PATTERN = Pattern.compile("(?i).*select.*\\*.*from.*"); - - @Override - public List nodesToVisit() { - return Arrays.asList(Kind.REGULAR_STRING_LITERAL); - } - - @Override - public void visitNode(Tree tree) { - - LiteralTree literal = (LiteralTree) tree; - if (PATTERN.matcher(literal.value()).matches()) { - context().newIssue(this, tree, ERROR_MESSAGE); - } - } -} diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopCheck.java deleted file mode 100644 index de7fd1729..000000000 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopCheck.java +++ /dev/null @@ -1,63 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import org.sonar.check.Rule; -import org.sonar.plugins.php.api.tree.SeparatedList; -import org.sonar.plugins.php.api.tree.Tree; -import org.sonar.plugins.php.api.tree.expression.ExpressionTree; -import org.sonar.plugins.php.api.tree.expression.ParenthesisedExpressionTree; -import org.sonar.plugins.php.api.tree.statement.DoWhileStatementTree; -import org.sonar.plugins.php.api.tree.statement.ForStatementTree; -import org.sonar.plugins.php.api.tree.statement.StatementTree; -import org.sonar.plugins.php.api.tree.statement.WhileStatementTree; -import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; - -import java.util.Arrays; -import java.util.List; -import java.util.regex.Pattern; - -@Rule(key = "EC3") -public class AvoidGettingSizeCollectionInLoopCheck extends PHPSubscriptionCheck { - - public static final String ERROR_MESSAGE = "Avoid getting the size of the collection in the loop"; - private static final Pattern PATTERN = Pattern.compile("\\b(?:count|sizeof|iterator_count)\\b"); - - @Override - public List nodesToVisit() { - return Arrays.asList( - Tree.Kind.FOR_STATEMENT, - Tree.Kind.ALTERNATIVE_FOR_STATEMENT, - Tree.Kind.WHILE_STATEMENT, - Tree.Kind.DO_WHILE_STATEMENT - ); - } - - @Override - public void visitNode(Tree tree) { - if (tree.is(Tree.Kind.FOR_STATEMENT) || tree.is(Tree.Kind.ALTERNATIVE_FOR_STATEMENT)) { - ForStatementTree conditionTree = (ForStatementTree) tree; - SeparatedList conditions = conditionTree.condition(); - - for (ExpressionTree condition : conditions) { - verifyAndLaunchError(condition.toString(), conditionTree); - } - } - - if (tree.is(Tree.Kind.WHILE_STATEMENT)) { - WhileStatementTree whileTree = (WhileStatementTree) tree; - ParenthesisedExpressionTree condition = whileTree.condition(); - verifyAndLaunchError(condition.expression().toString(), whileTree); - } - - if (tree.is(Tree.Kind.DO_WHILE_STATEMENT)) { - DoWhileStatementTree doWhileTree = (DoWhileStatementTree) tree; - ParenthesisedExpressionTree condition = doWhileTree.condition(); - verifyAndLaunchError(condition.expression().toString(), doWhileTree); - } - } - - private void verifyAndLaunchError(String condition, StatementTree conditionTree) { - if (PATTERN.matcher(condition).find()) { - context().newIssue(this, conditionTree, ERROR_MESSAGE); - } - } -} diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java deleted file mode 100644 index 5661853cb..000000000 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheck.java +++ /dev/null @@ -1,386 +0,0 @@ -/* - * SonarQube PHP Custom Rules Example - * Copyright (C) 2016-2016 SonarSource SA - * mailto:contact AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package fr.greencodeinitiative.php.checks; - -import org.sonar.check.Rule; -import org.sonar.plugins.php.api.tree.Tree; -import org.sonar.plugins.php.api.tree.Tree.Kind; -import org.sonar.plugins.php.api.tree.declaration.MethodDeclarationTree; -import org.sonar.plugins.php.api.tree.expression.BinaryExpressionTree; -import org.sonar.plugins.php.api.tree.expression.ExpressionTree; -import org.sonar.plugins.php.api.tree.expression.VariableIdentifierTree; -import org.sonar.plugins.php.api.tree.statement.*; -import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * FUNCTIONAL DESCRIPTION : please see ASCIIDOC description file of this rule (inside `ecocode-rules-spcifications`) - * TECHNICAL CHOICES : - * - Kind.IF_STATEMENT, Kind.ELSE_STATEMENT, Kind.ELSEIF_STATEMENT not used because it isn't possible - * to keep parent references to check later if variables already used or not in parent tree - * - only one way to keep parent history : manually go throw the all tree and thus, start at method declaration - * - an "ELSE" statement is considered as a second IF statement using the same variables used on previous - * - IF and ELSEIF statements are considered as an IF statement - */ -@Rule(key = "EC2") -public class AvoidMultipleIfElseStatementCheck extends PHPSubscriptionCheck { - - public static final String ERROR_MESSAGE = "Use a switch statement instead of multiple if-else if possible"; - - // data structure for following usage of variable inside all the AST tree - private VariablesPerLevelDataStructure variablesStruct = new VariablesPerLevelDataStructure(); - - // only visit each method to keep data of all conditional tree - // with IF, ELSE or ELSEIF statements, we can't keep all data of conditional tree - @Override - public List nodesToVisit() { - return List.of(Kind.METHOD_DECLARATION); - } - - @Override - public void visitNode(@SuppressWarnings("NullableProblems") Tree pTree) { - - MethodDeclarationTree method = (MethodDeclarationTree)pTree; - - if (!method.body().is(Kind.BLOCK)) { - return; - } - - // reinit data structure before each method analysis - variablesStruct = new VariablesPerLevelDataStructure(); - - // starting visit - visitNodeContent(((BlockTree) method.body()).statements(), 0); - - } - - /** - * Visit all content of a node for one level (with its statements list) - * - * @param pLstStatements statements list of current node - * @param pLevel level of current node - */ - private void visitNodeContent(List pLstStatements, int pLevel) { - if (pLstStatements == null || pLstStatements.isEmpty()) { - return; - } - - for (StatementTree statement : pLstStatements) { - if (statement.is(Kind.BLOCK)) { - // the cirrent node is a block : visit block content - visitNodeContent(((BlockTree)statement).statements(), pLevel); - } else if (statement.is(Kind.IF_STATEMENT)) { - visitIfNode((IfStatementTree)statement, pLevel); - } - } - } - - /** - * Visit an IF type node - * @param pIfTree the current node (Tree type) - * @param pLevel the level of node - */ - private void visitIfNode(IfStatementTree pIfTree, int pLevel) { - - if (pIfTree == null) return; - - // init current if structure with cleaning child levels - variablesStruct.reinitVariableUsageForLevel(pLevel + 1); - // init current if structure with cleaning for ELSE process checking - variablesStruct.reinitVariableUsageForLevelForCurrentIfStruct(pLevel); - - // analyze condition variables and raise error if needed - computeIfVariables(pIfTree, pLevel); - - // visit the content of if block - visitNodeContent(pIfTree.statements(), pLevel + 1); - - // analyze ELSEIF clauses - if (pIfTree.elseifClauses() != null && !pIfTree.elseifClauses().isEmpty()) { - for (ElseifClauseTree elseifClause : pIfTree.elseifClauses()) { - visitElseIfNode(elseifClause, pLevel); - } - } - - // analyze ELSE clause - visitElseNode(pIfTree.elseClause(), pLevel); - - } - - /** - * Analyze and compute variables usage for IF AST structure - * @param pIfTree IF node - * @param pLevel the level of IF node - */ - private void computeIfVariables(IfStatementTree pIfTree, int pLevel) { - - if (pIfTree.condition() == null) return; - - // analysing content of conditions of IF node - ExpressionTree expr = pIfTree.condition().expression(); - if (expr instanceof BinaryExpressionTree) { - computeConditionVariables((BinaryExpressionTree) expr, pLevel); - } - - } - - /** - * Analyze and compute variables usage for Expression structure - * @param pBinExprTree binary expression to analyze - * @param pLevel The level of binary expression - */ - private void computeConditionVariables(BinaryExpressionTree pBinExprTree, int pLevel) { - - // if multiple conditions, continue with each part of complex expression - if (pBinExprTree.is(Kind.CONDITIONAL_AND) || pBinExprTree.is(Kind.CONDITIONAL_OR)) { - if (pBinExprTree.leftOperand() instanceof BinaryExpressionTree) { - computeConditionVariables((BinaryExpressionTree) pBinExprTree.leftOperand(), pLevel); - } - if (pBinExprTree.rightOperand() instanceof BinaryExpressionTree) { - computeConditionVariables((BinaryExpressionTree) pBinExprTree.rightOperand(), pLevel); - } - } else if (pBinExprTree.is(Kind.EQUAL_TO) - || pBinExprTree.is(Kind.NOT_EQUAL_TO) - || pBinExprTree.is(Kind.GREATER_THAN) - || pBinExprTree.is(Kind.GREATER_THAN_OR_EQUAL_TO) - || pBinExprTree.is(Kind.LESS_THAN_OR_EQUAL_TO) - || pBinExprTree.is(Kind.LESS_THAN) - ) { - // continue analyze with variables if some key-words are found - if (pBinExprTree.leftOperand().is(Kind.VARIABLE_IDENTIFIER)) { - computeVariables((VariableIdentifierTree) pBinExprTree.leftOperand(), pLevel); - } - if (pBinExprTree.rightOperand().is(Kind.VARIABLE_IDENTIFIER)) { - computeVariables((VariableIdentifierTree) pBinExprTree.rightOperand(), pLevel); - } - } - } - - /** - * Analyze and compute variables usage for Variable AST structure - * @param pVarIdTree The Variable AST structure - * @param pLevel the level of structure - */ - private void computeVariables(VariableIdentifierTree pVarIdTree, int pLevel) { - if (pVarIdTree.variableExpression().is(Kind.VARIABLE_IDENTIFIER)) { - // increment the variable counter to list of all variables - int nbUsed = variablesStruct.incrementVariableUsageForLevel(pVarIdTree.text(), pLevel); - - // increment variable counter to list of variables already declared for current if or elseif struture - variablesStruct.incrementVariableUsageForLevelForCurrentIfStruct(pVarIdTree.text(), pLevel); - - // raise an error if maximum - if (nbUsed > 2) { - context().newIssue(this, pVarIdTree, ERROR_MESSAGE); - } - } - } - - /** - * Analyze and compute variables usage for ELSEIF AST structure - * @param pElseIfTree ELSEIF node - * @param pLevel the level of ELSEIF node - */ - private void visitElseIfNode(ElseifClauseTree pElseIfTree, int pLevel) { - - if (pElseIfTree == null) { return; } - - // init current if structure with cleaning child levels - variablesStruct.reinitVariableUsageForLevel(pLevel + 1); - - // init current if structure with cleaning for else verification - variablesStruct.reinitVariableUsageForLevelForCurrentIfStruct(pLevel); - - // analyze variables and raise error if needed - computeElseIfVariables(pElseIfTree, pLevel); - - // go to next child level - visitNodeContent(pElseIfTree.statements(), pLevel + 1); - } - - /** - * Analyze and compute variables usage for ELSEIF AST structure - * @param pElseIfTree ELSEIF node - * @param pLevel the level of ELSEIF node - */ - private void computeElseIfVariables(ElseifClauseTree pElseIfTree, int pLevel) { - - if (pElseIfTree.condition() == null) return; - - ExpressionTree expr = pElseIfTree.condition().expression(); - if (expr instanceof BinaryExpressionTree) { - computeConditionVariables((BinaryExpressionTree) expr, pLevel); - } - - } - - /** - * Analyze and compute variables usage for ELSE AST structure - * @param pElseTree ELSE node - * @param pLevel the level of ELSE node - */ - private void visitElseNode(ElseClauseTree pElseTree, int pLevel) { - - if (pElseTree == null) { return; } - - // analyze variables and raise error if needed - computeElseVariables(pElseTree, pLevel); - - // go to next child level - visitNodeContent(pElseTree.statements(), pLevel + 1); - } - - /** - * Analyze and compute variables usage for ELSE AST structure - * @param pElseTree ELSE node - * @param pLevel the level of ELSE node - */ - private void computeElseVariables(ElseClauseTree pElseTree, int pLevel) { - - for (Map.Entry entry : variablesStruct.getVariablesForCurrentIfStruct(pLevel).entrySet()) { - String variableName = entry.getKey(); - - // increment usage of all variables in the same level of ELSE staetement - int nbUsed = variablesStruct.incrementVariableUsageForLevel(variableName, pLevel); - - // increment variable counter to list of variables already declared for current if or elseif struture - variablesStruct.incrementVariableUsageForLevelForCurrentIfStruct(variableName, pLevel); - - // raise an error if maximum - if (nbUsed > 2) { - context().newIssue(this, pElseTree, ERROR_MESSAGE); - } - } - } - - /** - * Complex data structure representing variables counters per AST level (cumulative counts with parent levels) - * Map> ==> - * - Key : index of Level (0 = first level) - * - Value : Map - * - Key : name of variable in the current or parent level - * - Value : number of usage of this variable in an IF statement in current level or one of parent levels - * - */ - private static class VariablesPerLevelDataStructure { - - // global map variable counters per level - private final Map> mapVariablesPerLevel; - - // map variable counters per level for current If / ElseIf structure - // purpose : used by compute variables Else process (because Else structure is particular : - // we don't know previous variables and we need previous If / ElseIf structure to know variables) - private final Map> mapVariablesPerLevelForCurrentIfStruct; - - public VariablesPerLevelDataStructure() { - mapVariablesPerLevel = new HashMap<>(10); - mapVariablesPerLevelForCurrentIfStruct = new HashMap<>(10); - } - - /** - * increment variable counters on global map - */ - public int incrementVariableUsageForLevel(String variableName, int pLevel) { - return internalIncrementVariableUsage(mapVariablesPerLevel, variableName, pLevel); - } - - /** - * increment variable counters on input map - */ - private int internalIncrementVariableUsage(Map> pDataMap, String variableName, int pLevel) { - - // get variable usage map for current level and init if null - Map variablesMap = pDataMap.computeIfAbsent(pLevel, k -> new HashMap<>(5)); - - // get usage from parent if needed - Integer nbUsed = variablesMap.get(variableName); - if (nbUsed == null) { - Integer nbParentUsed = internalGetVariableUsageOfNearestParent(pDataMap, variableName, pLevel - 1); - nbUsed = nbParentUsed == null ? 0 : nbParentUsed; - } - - // increment usage for current level - nbUsed++; - variablesMap.put(variableName, nbUsed); - - return nbUsed; - } - - /** - * get usage of a variable in top tree (nearest top parent) - */ - private Integer internalGetVariableUsageOfNearestParent(Map> pDataMap, String variableName, int pLevel) { - - Integer nbParentUsed = null; - for (int i = pLevel; i >= 0 && nbParentUsed == null; i--) { - Map variablesParentLevelMap = pDataMap.get(i); - nbParentUsed = variablesParentLevelMap.get(variableName); - } - - return nbParentUsed; - } - - /** - * reinitialization of variable usages for input level and global map - */ - public void reinitVariableUsageForLevel(int pLevel) { - internalReinitVariableUsageForLevelForCurrentIfStruct(mapVariablesPerLevel, pLevel); - } - - /** - * reinitialization of variable usages in input level in input map - */ - private void internalReinitVariableUsageForLevelForCurrentIfStruct(Map> pDataMap, int pLevel) { - if (pDataMap.get(pLevel) == null) { return; } - - // cleaning of current If Structure beginning at level specified - for (int i = pLevel; i < pDataMap.size(); i++) { - pDataMap.remove(i); - } - - } - - /** - * reinitialization of variable usages for input level on if/elseif map - */ - public void reinitVariableUsageForLevelForCurrentIfStruct(int pLevel) { - internalReinitVariableUsageForLevelForCurrentIfStruct(mapVariablesPerLevelForCurrentIfStruct, pLevel); - } - - /** - * increment variable counters on if/elseif map - */ - public void incrementVariableUsageForLevelForCurrentIfStruct(String variableName, int pLevel) { - internalIncrementVariableUsage(mapVariablesPerLevelForCurrentIfStruct, variableName, pLevel); - } - - /** - * get usage of a variable in a level on if/elseif map - */ - public Map getVariablesForCurrentIfStruct(int pLevel) { - return mapVariablesPerLevelForCurrentIfStruct.get(pLevel); - } - - } - -} diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheck.java deleted file mode 100644 index 0badb8c2b..000000000 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheck.java +++ /dev/null @@ -1,82 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.util.Arrays; -import java.util.List; -import java.util.regex.Pattern; - -import org.sonar.check.Rule; -import org.sonar.plugins.php.api.tree.Tree; -import org.sonar.plugins.php.api.tree.Tree.Kind; -import org.sonar.plugins.php.api.tree.statement.BlockTree; -import org.sonar.plugins.php.api.tree.statement.DoWhileStatementTree; -import org.sonar.plugins.php.api.tree.statement.ExpressionStatementTree; -import org.sonar.plugins.php.api.tree.statement.ForEachStatementTree; -import org.sonar.plugins.php.api.tree.statement.ForStatementTree; -import org.sonar.plugins.php.api.tree.statement.IfStatementTree; -import org.sonar.plugins.php.api.tree.statement.StatementTree; -import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC72") -@DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S72") -public class AvoidSQLRequestInLoopCheck extends PHPSubscriptionCheck { - - public static final String ERROR_MESSAGE = "Avoid SQL request in loop"; - private static final Pattern PATTERN = Pattern.compile("(mysql(i::|_)query\\s*\\(.*)|(oci_execute\\(.*)"); - - @Override - public List nodesToVisit() { - return Arrays.asList(Kind.FOR_STATEMENT, Kind.FOREACH_STATEMENT, Kind.DO_WHILE_STATEMENT); - } - - @Override - public void visitNode(Tree tree) { - if (tree.is(Kind.FOR_STATEMENT)) { - StatementTree stTree = ((ForStatementTree) tree).statements().get(0); - if (stTree.is(Kind.BLOCK)) { - visitBlockNode((BlockTree) stTree); - } - } - - if (tree.is(Kind.FOREACH_STATEMENT)) { - StatementTree stTree = ((ForEachStatementTree) tree).statements().get(0); - if (stTree.is(Kind.BLOCK)) { - visitBlockNode((BlockTree) stTree); - } - } - - if (tree.is(Kind.DO_WHILE_STATEMENT)) { - StatementTree stTree = ((DoWhileStatementTree) tree).statement(); - if (stTree.is(Kind.BLOCK)) { - visitBlockNode((BlockTree) stTree); - } - } - } - - private void visitBlockNode(BlockTree block) { - block.statements().forEach(this::visiteChildNode); - } - - private void visiteChildNode(Tree tree) { - if (tree.is(Kind.EXPRESSION_STATEMENT)) { - ExpressionStatementTree expressionStatementTree = (ExpressionStatementTree) tree; - String expression = expressionStatementTree.expression().toString(); - verifyIfThereIsAError(expression, expressionStatementTree); - } - - if (tree.is(Kind.IF_STATEMENT)) { - StatementTree statementTree = ((IfStatementTree) tree).statements().get(0); - if (statementTree.is(Kind.BLOCK)) { - visitBlockNode((BlockTree) statementTree); - } else { - visiteChildNode(statementTree); - } - } - } - - private void verifyIfThereIsAError(String expression, ExpressionStatementTree expressionStatementTree) { - if (PATTERN.matcher(expression).find()) - context().newIssue(this, expressionStatementTree, ERROR_MESSAGE); - } - -} diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.java deleted file mode 100644 index 6aa9943a7..000000000 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements.java +++ /dev/null @@ -1,27 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.util.Collections; -import java.util.List; - -import org.sonar.check.Rule; -import org.sonar.plugins.php.api.tree.Tree; -import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC34") -@DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S34") -public class AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements extends PHPSubscriptionCheck { - - public static final String ERROR_MESSAGE = "Avoid using try-catch"; - - @Override - public List nodesToVisit() { - return Collections.singletonList(Tree.Kind.TRY_STATEMENT); - } - - @Override - public void visitNode(Tree tree) { - context().newIssue(this, tree, ERROR_MESSAGE); - } - -} diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheck.java deleted file mode 100644 index 1b37a96e5..000000000 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheck.java +++ /dev/null @@ -1,24 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.util.regex.Pattern; - -import org.sonar.check.Rule; -import org.sonar.plugins.php.api.tree.declaration.FunctionDeclarationTree; -import org.sonar.plugins.php.api.visitors.PHPVisitorCheck; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC4") -@DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "D4") -public class AvoidUsingGlobalVariablesCheck extends PHPVisitorCheck { - - public static final String ERROR_MESSAGE = "Prefer local variables to globals"; - - private static final Pattern PATTERN = Pattern.compile("^.*(global \\$|\\$GLOBALS).*$", Pattern.CASE_INSENSITIVE); - - @Override - public void visitFunctionDeclaration(FunctionDeclarationTree tree) { - if (PATTERN.matcher(tree.body().toString()).matches()) { - context().newIssue(this, tree, String.format(ERROR_MESSAGE, tree.body().toString())); - } - } -} diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java deleted file mode 100644 index 904cd404b..000000000 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/IncrementCheck.java +++ /dev/null @@ -1,28 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.util.Collections; -import java.util.List; - -import org.sonar.check.Rule; -import org.sonar.plugins.php.api.tree.Tree; -import org.sonar.plugins.php.api.tree.Tree.Kind; -import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC67") -@DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S67") -public class IncrementCheck extends PHPSubscriptionCheck { - - public static final String ERROR_MESSAGE = "Remove the usage of $i++. prefer ++$i"; - - @Override - public List nodesToVisit() { - return Collections.singletonList(Kind.POSTFIX_INCREMENT); - } - - @Override - public void visitNode(Tree tree) { - context().newIssue(this, tree, ERROR_MESSAGE); - } - -} diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoop.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoop.java deleted file mode 100644 index 999d0cfe5..000000000 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoop.java +++ /dev/null @@ -1,51 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.util.Collections; -import java.util.List; - -import org.sonar.check.Rule; -import org.sonar.plugins.php.api.tree.SeparatedList; -import org.sonar.plugins.php.api.tree.Tree; -import org.sonar.plugins.php.api.tree.Tree.Kind; -import org.sonar.plugins.php.api.tree.expression.BinaryExpressionTree; -import org.sonar.plugins.php.api.tree.expression.ExpressionTree; -import org.sonar.plugins.php.api.tree.statement.ForStatementTree; -import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC69") -@DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "S69") -public class NoFunctionCallWhenDeclaringForLoop extends PHPSubscriptionCheck { - - public static final String ERROR_MESSAGE = "Do not call a function in for-type loop declaration"; - - @Override - public List nodesToVisit() { - return Collections.singletonList(Kind.FOR_STATEMENT); - } - - @Override - public void visitNode(Tree tree) { - ForStatementTree method = (ForStatementTree) tree; - checkExpressionsTree(method.update()); - checkExpressionsTree(method.condition()); - } - - public void checkExpressionsTree(SeparatedList treeSeparatedList) { - treeSeparatedList.forEach(this::checkBothSideExpression); - } - - public void checkBothSideExpression(ExpressionTree expressionTree) { - if (expressionTree.getKind().getAssociatedInterface() == BinaryExpressionTree.class) { - BinaryExpressionTree binaryExpressionTree = (BinaryExpressionTree) expressionTree; - isFunctionCall(binaryExpressionTree.leftOperand()); - isFunctionCall(binaryExpressionTree.rightOperand()); - } else - isFunctionCall(expressionTree); - } - - public void isFunctionCall(ExpressionTree expressionTree) { - if (expressionTree.getKind() == Tree.Kind.FUNCTION_CALL) - context().newIssue(this, expressionTree, ERROR_MESSAGE); - } -} diff --git a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperations.java b/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperations.java deleted file mode 100644 index 1285fb4d7..000000000 --- a/php-plugin/src/main/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperations.java +++ /dev/null @@ -1,93 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.stream.Collectors; - -import org.sonar.check.Rule; -import org.sonar.plugins.php.api.tree.ScriptTree; -import org.sonar.plugins.php.api.tree.Tree; -import org.sonar.plugins.php.api.tree.declaration.ClassDeclarationTree; -import org.sonar.plugins.php.api.tree.declaration.ClassMemberTree; -import org.sonar.plugins.php.api.tree.declaration.MethodDeclarationTree; -import org.sonar.plugins.php.api.tree.expression.FunctionCallTree; -import org.sonar.plugins.php.api.tree.statement.StatementTree; -import org.sonar.plugins.php.api.visitors.PHPSubscriptionCheck; -import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; - -@Rule(key = "EC22") -@DeprecatedRuleKey(repositoryKey = "gci-php", ruleKey = "D2") -public class UseOfMethodsForBasicOperations extends PHPSubscriptionCheck { - - protected static final String ERROR_MESSAGE = "Use of methods for basic operations"; - - @Override - public List nodesToVisit() { - return Collections.singletonList(Tree.Kind.FUNCTION_CALL); - } - - @Override - public void visitNode(Tree tree) { - AtomicBoolean contains = new AtomicBoolean(false); - - final FunctionCallTree functionTree = ((FunctionCallTree) tree); - final String functionName = functionTree.callee().toString(); - - final List parents = this.getAllParent(tree, new ArrayList<>()); - - parents.forEach(parent -> { - if (parent.is(Tree.Kind.SCRIPT)) { - - final ScriptTree specific = (ScriptTree) parent; - final List trees = specific.statements(); - - trees.forEach(statement -> { - - if (statement.is(Tree.Kind.CLASS_DECLARATION)) { - - final List methodDeclarations = ((ClassDeclarationTree) statement).members() - .stream() - .filter(member -> member.is(Tree.Kind.METHOD_DECLARATION)) - .map(MethodDeclarationTree.class::cast) - .filter(declarationTree -> this.isFunctionDeclared(declarationTree, functionName)) - .collect(Collectors.toList()); - - if (methodDeclarations != null && !methodDeclarations.isEmpty()) { - contains.set(true); - } - } - }); - } - }); - - if (!contains.get()) { - context().newIssue(this, tree, ERROR_MESSAGE); - } - } - - public boolean isFunctionDeclared(final MethodDeclarationTree method, final String name) { - if (method == null) { - return false; - } - - return method.name().text() - .trim() - .equals(name.trim()); - } - - public List getAllParent(final Tree tree, final List list) { - if (tree == null) - return list; - - final Tree parent = tree.getParent(); - - if (parent == null) - return list; - - list.add(parent); - - return this.getAllParent(parent, list); - } -} diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java deleted file mode 100644 index 9139c7c4e..000000000 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpPluginTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2023 Green Code Initiative - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.php; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.sonar.api.Plugin; -import org.sonar.api.SonarRuntime; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -class PhpPluginTest { - private Plugin.Context context; - - @BeforeEach - void init() { - SonarRuntime sonarRuntime = mock(SonarRuntime.class); - context = new Plugin.Context(sonarRuntime); - new PHPPlugin().define(context); - } - - @Test - void test() { - assertThat(context.getExtensions()).hasSize(1); - } - -} diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java deleted file mode 100644 index e64c7e593..000000000 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/PhpRuleRepositoryTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2023 Green Code Initiative - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package fr.greencodeinitiative.php; - -import org.assertj.core.api.SoftAssertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.sonar.api.SonarRuntime; -import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.api.utils.Version; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -class PhpRuleRepositoryTest { - - private RulesDefinition.Repository repository; - - @BeforeEach - void init() { - // TODO: Remove this check after Git repo split - /* - On an IDE (like IntelliJ), if the developer runs the unit tests without building/generating the Maven goals on the - "ecocode-rules-specifications" module before, the unit tests will not see the generated HTML descriptions (from ASCIIDOC files). - The developer must therefore configure his IDE to build the `ecocode-rules-specifications` module before launching the Tests. - - When the `php-plugin` submodule is in a specific Git repository, `ecocode-rules-specifications` will be fetched from a classic - external Maven dependency. There will therefore no longer be any need to perform this specific configuration. - */ - if (PhpRuleRepository.class.getResource("/io/ecocode/rules/php/EC4.json") == null) { - String message = "'ecocode-rules-specification' resources corrupted. Please check build of 'ecocode-rules-specification' module"; - if (System.getProperties().keySet().stream().anyMatch(k -> k.toString().startsWith("idea."))) { - message += "\n\nOn 'IntelliJ IDEA':" + - "\n1. go to settings :" + - "\n > Build, Execution, Deployment > Build Tools > Maven > Runner" + - "\n2. check option:" + - "\n > Delegate IDE build/run actions to Maven" + - "\n3. Click on menu: " + - "\n > Build > Build Project" - ; - } - fail(message); - } - - final SonarRuntime sonarRuntime = mock(SonarRuntime.class); - doReturn(Version.create(0, 0)).when(sonarRuntime).getApiVersion(); - PhpRuleRepository rulesDefinition = new PhpRuleRepository(sonarRuntime); - RulesDefinition.Context context = new RulesDefinition.Context(); - rulesDefinition.define(context); - repository = context.repository(rulesDefinition.repositoryKey()); - } - - @Test - @DisplayName("Test repository metadata") - void testMetadata() { - assertThat(repository.name()).isEqualTo("ecoCode"); - assertThat(repository.language()).isEqualTo("php"); - assertThat(repository.key()).isEqualTo("ecocode-php"); - } - - @Test - void testRegistredRules() { - assertThat(repository.rules()).hasSize(10); - } - - @Test - @DisplayName("All rule keys must be prefixed by 'EC'") - void testRuleKeyPrefix() { - SoftAssertions assertions = new SoftAssertions(); - repository.rules().forEach( - rule -> assertions.assertThat(rule.key()).startsWith("EC") - ); - assertions.assertAll(); - } - - @Test - void testAllRuleParametersHaveDescription() { - SoftAssertions assertions = new SoftAssertions(); - repository.rules().stream() - .flatMap(rule -> rule.params().stream()) - .forEach(param -> assertions.assertThat(param.description()) - .as("description for " + param.key()) - .isNotEmpty()); - assertions.assertAll(); - } -} diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheckTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheckTest.java deleted file mode 100644 index 9a68f8ac3..000000000 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidDoubleQuoteCheckTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.io.File; - -import org.junit.Test; -import org.sonar.plugins.php.api.tests.PHPCheckTest; -import org.sonar.plugins.php.api.tests.PhpTestFile; - -public class AvoidDoubleQuoteCheckTest { - - @Test - public void test() throws Exception { - PHPCheckTest.check(new AvoidDoubleQuoteCheck(), new PhpTestFile(new File("src/test/resources/checks/AvoidDoubleQuote.php"))); - } - -} diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheckTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheckTest.java deleted file mode 100644 index de90bec78..000000000 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidFullSQLRequestCheckTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.io.File; - -import org.junit.Test; -import org.sonar.plugins.php.api.tests.PHPCheckTest; -import org.sonar.plugins.php.api.tests.PhpTestFile; - -public class AvoidFullSQLRequestCheckTest { - - @Test - public void test() { - PHPCheckTest.check(new AvoidFullSQLRequestCheck(), new PhpTestFile(new File("src/test/resources/checks/AvoidFullSQLRequest.php"))); - } -} diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopTest.java deleted file mode 100644 index 85de2bdc4..000000000 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidGettingSizeCollectionInLoopTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import org.junit.Test; -import org.sonar.plugins.php.api.tests.PHPCheckTest; -import org.sonar.plugins.php.api.tests.PhpTestFile; - -import java.io.File; - -public class AvoidGettingSizeCollectionInLoopTest { - - @Test - public void test() throws Exception { - PHPCheckTest.check(new AvoidGettingSizeCollectionInLoopCheck(), new PhpTestFile(new File("src/test/resources/checks/AvoidGettingSizeCollectionInLoop.php"))); - } -} diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheckTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheckTest.java deleted file mode 100644 index 50b6bfbef..000000000 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidMultipleIfElseStatementCheckTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * SonarQube PHP Custom Rules Example - * Copyright (C) 2016-2016 SonarSource SA - * mailto:contact AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package fr.greencodeinitiative.php.checks; - -import org.junit.Test; -import org.sonar.plugins.php.api.tests.PHPCheckTest; -import org.sonar.plugins.php.api.tests.PhpTestFile; - -import java.io.File; - -/** - * Test class to test the check implementation. - */ -public class AvoidMultipleIfElseStatementCheckTest { - - @Test - public void test() throws Exception { - PHPCheckTest.check(new AvoidMultipleIfElseStatementCheck(), new PhpTestFile(new File("src/test/resources/checks/AvoidMultipleIfElseStatement.php"))); - } - -} diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheckTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheckTest.java deleted file mode 100644 index e124b8547..000000000 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidSQLRequestInLoopCheckTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.io.File; - -import org.junit.Test; -import org.sonar.plugins.php.api.tests.PHPCheckTest; -import org.sonar.plugins.php.api.tests.PhpTestFile; - -public class AvoidSQLRequestInLoopCheckTest { - - @Test - public void test() throws Exception { - PHPCheckTest.check(new AvoidSQLRequestInLoopCheck(), new PhpTestFile(new File("src/test/resources/checks/AvoidSQLRequestInLoop.php"))); - } -} diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheckNOKfailsAllTryStatementsTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheckNOKfailsAllTryStatementsTest.java deleted file mode 100644 index d9867e9f1..000000000 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidTryCatchFinallyCheckNOKfailsAllTryStatementsTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.io.File; - -import org.junit.Test; -import org.sonar.plugins.php.api.tests.PHPCheckTest; -import org.sonar.plugins.php.api.tests.PhpTestFile; - -public class AvoidTryCatchFinallyCheckNOKfailsAllTryStatementsTest { - - @Test - public void test() throws Exception { - PHPCheckTest.check(new AvoidTryCatchFinallyCheck_NOK_failsAllTryStatements(), new PhpTestFile(new File("src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php"))); - } - -} diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheckTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheckTest.java deleted file mode 100644 index ca0256117..000000000 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/AvoidUsingGlobalVariablesCheckTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import org.junit.Test; -import org.sonar.plugins.php.api.tests.PHPCheckTest; -import org.sonar.plugins.php.api.tests.PhpTestFile; - -import java.io.File; - -public class AvoidUsingGlobalVariablesCheckTest { - - @Test - public void test() throws Exception { - PHPCheckTest.check(new AvoidUsingGlobalVariablesCheck(), new PhpTestFile(new File("src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php"))); - } - -} diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/IncrementCheckTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/IncrementCheckTest.java deleted file mode 100644 index 7da3216e5..000000000 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/IncrementCheckTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.io.File; - -import org.junit.Test; -import org.sonar.plugins.php.api.tests.PHPCheckTest; -import org.sonar.plugins.php.api.tests.PhpTestFile; - -public class IncrementCheckTest { - - @Test - public void test() throws Exception { - PHPCheckTest.check(new IncrementCheck(), new PhpTestFile(new File("src/test/resources/checks/IncrementCheck.php"))); - } - -} diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoopTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoopTest.java deleted file mode 100644 index 2d18b0646..000000000 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/NoFunctionCallWhenDeclaringForLoopTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.io.File; - -import org.junit.Test; -import org.sonar.plugins.php.api.tests.PHPCheckTest; -import org.sonar.plugins.php.api.tests.PhpTestFile; - -public class NoFunctionCallWhenDeclaringForLoopTest { - - @Test - public void test() throws Exception { - PHPCheckTest.check(new NoFunctionCallWhenDeclaringForLoop(), new PhpTestFile(new File("src/test/resources/checks/NoFunctionCallWhenDeclaringForLoop.php"))); - } -} diff --git a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperationsTest.java b/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperationsTest.java deleted file mode 100644 index 1627d94a4..000000000 --- a/php-plugin/src/test/java/fr/greencodeinitiative/php/checks/UseOfMethodsForBasicOperationsTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package fr.greencodeinitiative.php.checks; - -import java.io.File; - -import org.junit.Test; -import org.sonar.plugins.php.api.tests.PHPCheckTest; -import org.sonar.plugins.php.api.tests.PhpTestFile; - -public class UseOfMethodsForBasicOperationsTest { - - @Test - public void test() throws Exception { - PHPCheckTest.check(new UseOfMethodsForBasicOperations(), new PhpTestFile(new File("src/test/resources/checks/UseOfMethodsForBasicOperations.php"))); - } -} diff --git a/php-plugin/src/test/resources/checks/AvoidDoubleQuote.php b/php-plugin/src/test/resources/checks/AvoidDoubleQuote.php deleted file mode 100644 index 30e0a4795..000000000 --- a/php-plugin/src/test/resources/checks/AvoidDoubleQuote.php +++ /dev/null @@ -1,24 +0,0 @@ -'; -echo "
      "; // NOK {{Avoid using double quote ("), prefer using simple quote (')}} -echo $age; - -$identite = $lastName .' '. $name; -echo $identite; - -myFunction($name, $age, $isStudent); - -myFunction("name", "age", "isStudent"); // NOK {{Avoid using double quote ("), prefer using simple quote (')}} - -myFunction('name', 'age', 'isStudent'); - -myFunction("name", 'age', "isStudent"); // NOK {{Avoid using double quote ("), prefer using simple quote (')}} diff --git a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php b/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php deleted file mode 100644 index 4ef22c15c..000000000 --- a/php-plugin/src/test/resources/checks/AvoidFullSQLRequest.php +++ /dev/null @@ -1,25 +0,0 @@ -SqlCall('SELECT * FROM'); // NOK {{Don't use the query SELECT * FROM}} - OtherClass->SqlCall('SeLeCt DiStInCt * FrOm'); // NOK {{Don't use the query SELECT * FROM}} - OtherClass->SqlCall('select name from'); - } - - public function passeAsVariable() - { - $sqlQuery1 = 'SELECT * FROM'; // NOK {{Don't use the query SELECT * FROM}} - $sqlQuery2 = 'SeLeCt DiStInCt * FrOm'; // NOK {{Don't use the query SELECT * FROM}} - $sqlQuery3 = 'select name from'; - OtherClass->SqlCall($sqlQuery1); - OtherClass->SqlCall($sqlQuery2); - OtherClass->SqlCall($sqlQuery3); - } -} diff --git a/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInLoop.php b/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInLoop.php deleted file mode 100644 index 543a8b4a4..000000000 --- a/php-plugin/src/test/resources/checks/AvoidGettingSizeCollectionInLoop.php +++ /dev/null @@ -1,231 +0,0 @@ - $i; ++$i) { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); -} - -$size = count($array); -for ($i = 0; $size > $i; ++$i) { // Compliant - var_dump($array[$i]); -} - -for ($i = 0; sizeof($array) > $i; ++$i) { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); -} - -$size = sizeof($array); -for ($i = 0; $size > $i; ++$i) { // Compliant - var_dump($array[$i]); -} - -for ($i = 0; iterator_count(new ArrayIterator($array)) > $i; ++$i) { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); -} - -$size = iterator_count(new ArrayIterator($array)); -for ($i = 0; $size > $i; ++$i) { // Compliant - var_dump($array[$i]); -} - -/** - * WHILE STATEMENTS // RIGHT OPERAND - */ -$i = 0; -while ($i < count($array)) { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); - ++$i; -} - -$i = 0; -$size = count($array); -while ($i < $size) { // Compliant - var_dump($array[$i]); - ++$i; -} - -$i = 0; -while ($i < sizeof($array)) { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); - ++$i; -} - -$i = 0; -$size = sizeof($array); -while ($i < $size) { // Compliant - var_dump($array[$i]); - ++$i; -} - -$i = 0; -while ($i < iterator_count(new ArrayIterator($array))) { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); - ++$i; -} - -$i = 0; -$size = iterator_count(new ArrayIterator($array)); -while ($i < $size) { // Compliant - var_dump($array[$i]); - ++$i; -} - -/** - * WHILE STATEMENTS // LEFT OPERAND - */ -$i = 0; -while (count($array) > $i) { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); - ++$i; -} - -$i = 0; -$size = count($array); -while ($size> $i) { // Compliant - var_dump($array[$i]); - ++$i; -} - -$i = 0; -while (sizeof($array) > $i) { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); - ++$i; -} - -$i = 0; -$size = sizeof($array); -while ($size > $i) { // Compliant - var_dump($array[$i]); - ++$i; -} - -$i = 0; -while (iterator_count(new ArrayIterator($array)) > $i) { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); - ++$i; -} - -$i = 0; -$size = iterator_count(new ArrayIterator($array)); -while ($size > $i) { // Compliant - var_dump($array[$i]); - ++$i; -} - -/** - * DO WHILE STATEMENTS // RIGHT OPERAND - */ -$i = 0; -do { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); - ++$i; -} while ($i < count($array)); - -$i = 0; -$size = count($array); -do { - var_dump($array[$i]); - ++$i; -} while ($i < $size); // Compliant - -$i = 0; -do { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); - ++$i; -} while ($i < sizeof($array)); - -$i = 0; -$size = sizeof($array); -do { - var_dump($array[$i]); - ++$i; -} while ($i < $size); // Compliant - -$i = 0; -do { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); - ++$i; -} while ($i < iterator_count(new ArrayIterator($array))); - -$i = 0; -$size = iterator_count(new ArrayIterator($array)); -do { - var_dump($array[$i]); - ++$i; -} while ($i < $size); // Compliant - -/** - * DO WHILE STATEMENTS // LEFT OPERAND - */ -$i = 0; -do { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); - ++$i; -} while (count($array) > $i); - -$i = 0; -$size = count($array); -do { - var_dump($array[$i]); - ++$i; -} while ($size > $i); // Compliant - -$i = 0; -do { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); - ++$i; -} while (sizeof($array) > $i); - -$i = 0; -$size = sizeof($array); -do { - var_dump($array[$i]); - ++$i; -} while ($size > $i); // Compliant - -$i = 0; -do { // NOK {{Avoid getting the size of the collection in the loop}} - var_dump($array[$i]); - ++$i; -} while (iterator_count(new ArrayIterator($array)) > $i); - -$i = 0; -$size = iterator_count(new ArrayIterator($array)); -do { - var_dump($array[$i]); - ++$i; -} while ($size > $i); // Compliant diff --git a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php b/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php deleted file mode 100644 index 329179478..000000000 --- a/php-plugin/src/test/resources/checks/AvoidMultipleIfElseStatement.php +++ /dev/null @@ -1,453 +0,0 @@ - 1) { - $nb1 = 1; - } else { - $nb2 = 2; - } - - if ($nb2 == 2) { - $nb1 = 3; - } else { - $nb1 = 4; - } - - return $nb1; - } - - // COMPLIANT - // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements - // at the same level AND no problem with several IF staments at the same level using different variables - public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsedAtDiffLevels() - { - $nb1 = 0; - $nb2 = 0; - $nb3 = 0; - - if ($nb1 < 1) { - if ($nb2 == 2) { - $nb3 = 3; - } else { - $nb3 = 4; - } - } else { - $nb2 = 2; - } - - if ($nb3 >= 1) { - if ($nb2 == 2) { - $nb1 = 3; - } else { - $nb1 = 4; - } - } else { - $nb1 = 2; - } - - return $nb1; - } - - // COMPLIANT - // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements - // at the same level AND no problem with several IF staments at the same level using different variables - public function shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDiffVariablesUsedAtDiffLevelsScenario2() - { - $nb1 = 0; - $nb2 = 0; - $nb3 = 0; - - if ($nb1 <= 1) { - if ($nb2 == 2) { - if ($nb3 == 2) { - $nb3 = 3; - } else { - $nb3 = 4; - } - } else { - $nb3 = 4; - } - } else { - $nb2 = 2; - } - - if ($nb3 == 1) { - if ($nb2 == 2) { - $nb1 = 3; - } else { - $nb1 = 4; - } - } else { - $nb1 = 2; - } - - return $nb1; - } - - // COMPLIANT - // USE CASE : compliant use case to check if one variable is used maximum twice in different IF statements - public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInIfStatements() - { - $nb1 = 0; - - if ($nb1 == 1) { - $nb1 = 1; - } - - if ($nb1 == 2) { - $nb1 = 3; - } - - return $nb1; - } - - // COMPLIANT - // USE CASE : compliant use case to check if following is OK : - // - two uses of the same variable - // - usage of the same variable on different levels of IF statements - public function shouldBeCompliantBecauseSereralVariablesUsedMaximumTwiceInComposedElseStatements() - { - $nb1 = 0; - $nb2 = 0; - $nb3 = 0; - - if ($nb1 == 1) { - $nb1 = 2; - } else { - if ($nb2 == 2) { - $nb1 = 1; - } else { - if ($nb3 == 4) { - $nb1 = 3; - } else { - $nb1 = 6; - } - } - } - - return $nb1; - } - - // COMPLIANT - // USE CASE : compliant use case to check if following is OK : - // - two uses of the same variable - // - usage of the same variable on different kind of test statements (IF and ELSEIF) - public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInIfOrElseIfStatements() // Compliant - { - $nb1 = 0; - $nb2 = 10; - - if ($nb1 == 1) { - $nb2 = 1; - } elseif ($nb1 == $nb2) { - $nb2 = 2; - } - - return $nb2; - } - - // COMPLIANT - // USE CASE : compliant use case to check if following is OK : - // - two uses of the same variable - // - usage of the same variable on different kind of test statements (IF and ELSEIF) - public function shouldBeCompliantBecauseSeveralVariablesUsedMaximumTwiceInIfOrElseIfStatements() // Compliant - { - $nb1 = 0; - $nb2 = 10; - $nb3 = 3; - $nb4 = 1; - $nb5 = 2; - - if ($nb1 == 1) { - $nb2 = 1; - } elseif ($nb3 == $nb2) { - $nb2 = 2; - } elseif ($nb4 == $nb5) { - $nb2 = 4; - } else { - $nb2 = 3; - } - - return $nb2; - } - -// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// // -// // NON COMPLIANT use cases -// // -// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - // NON COMPLIANT - // USE CASE : Non compliant use case to check if following is NON OK : - // - two uses of the same variable - // - usage of the same variable on different levels of IF statements - public function shouldBeCompliantBecauseVariableUsedMaximumTwiceInComposedElseStatements() - { - $nb1 = 0; - - if ($nb1 == 1) { - $nb1 = 2; - } else { - if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 1; - } - } - - return $nb1; - } - - // NON COMPLIANT - // USE CASE : non compliant use case to check if a variable is not used max twice on several IF / ELSE statements - // at the same level - public function shouldBeNotCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsed() - { - $nb1 = 0; - $nb2 = 0; - $nb3 = 0; - - if ($nb3 == 1 - && $nb3 == 2 - && $nb3 == 3) { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 1; - } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb2 = 2; - } - - if ($nb2 == 2) { - $nb1 = 3; - } else { - $nb1 = 4; - } - - return $nb1; - } - - // NON COMPLIANT - // USE CASE : NON compliant use case to check if following is NOT COMPLIANT : - // one variable is used maximum in two IF / ELSE / ELSEIF statements - public function shouldBeNotCompliantBecauseVariablesIsUsedMoreThanTwice() - { - $nb1 = 0; - - if ($nb1 == 1) { - $nb1 = 2; - } else { - $nb1 = 3; - } - - if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 4; - } - - return $nb1; - } - - // NON COMPLIANT - // USE CASE : NON compliant use case to check if following is NOT OK : - // - same variable used maximum twice : no compliant because 2 IFs and 1 ELSE - public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInIfStatementsAtDifferentsLevels() - { - $nb1 = 0; - - if ($nb1 == 1) { - if ($nb1 == 2) { - $nb1 = 1; - } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 3; - } - } else { - $nb1 = 2; - } - - return $nb1; - } - - // NON COMPLIANT - // USE CASE : non compliant use case to check if following is NOT OK : - // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE - // - usage of the same variable on different levels of IF statements - public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatements() - { - $nb1 = 0; - - if ($nb1 == 1) { - $nb1 = 2; - } else { - if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 1; - } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 3; - } - } - - return $nb1; - } - - // NON COMPLIANT - // USE CASE : non compliant use case to check if following is NOT OK : - // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE - // - usage of the same variable on different levels of IF statements - public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatementsScenario2() - { - $nb1 = 0; - - if ($nb1 == 1) { - if ($nb1 == 3) { - $nb1 = 4; - } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 5; - } - } else { - if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 1; - } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 3; - } - } - - return $nb1; - } - - // NON COMPLIANT - // USE CASE : non compliant use case to check if following is NOT OK : - // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE - // - usage of the same variable on different levels of IF statements - public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatementsScenario3() - { - $nb1 = 0; - $nb2 = 0; - - if ($nb1 == 1) { - if ($nb1 == 3) { - $nb1 = 4; - } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 5; - } - } elseif ($nb2 == 2) { - if ($nb1 == 4) { - $nb1 = 5; - } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 6; - } - } - - return $nb1; - } - - // NON COMPLIANT - // USE CASE : non compliant use case to check if following is NOT OK : - // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE - // - usage of the same variable on different levels of IF statements - public function shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatementsScenario4() - { - $nb1 = 0; - $nb2 = 0; - - if ($nb1 == 1) { - if ($nb2 == 3) { - $nb1 = 4; - } else { - $nb1 = 5; - } - } elseif ($nb2 == 2) { - if ($nb1 == 3) { - $nb1 = 4; - } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 5; - } - } - - return $nb1; - } - - // NON COMPLIANT - // USE CASE : NON compliant use case to check if following is NOT OK : - // - the same variable must used maximum twice - // - usage of the same variable on different levels of IF / ELSE statements - public function shouldBeNotCompliantBecauseVariableUsedMaximumTwiceInComposedElseStatements() - { - $nb1 = 0; - - if ($nb1 == 1) { - $nb1 = 2; - } else { - if ($nb1 == 2) { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 1; - } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - if ($nb1 == 3) { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 4; - } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb1 = 5; - } - } - } - - return $nb1; - } - - // NON COMPLIANT - // USE CASE : NON compliant use case to check if following is NOT OK : - // - more than twice uses of the same variable - // - usage of the same variable on different kind of test statements (IF and ELSEIF) - public function shouldBeNotCompliantBecauseTheSameVariableIsUsedMoreThanTwice() // NOT Compliant - { - $nb1 = 0; - $nb2 = 10; - - if ($nb1 == 1) { - $nb2 = 1; - } elseif ($nb1 == $nb2) { - $nb2 = 2; - } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb2 = 4; - } - - return $nb2; - } - - // NON COMPLIANT - // USE CASE : NON compliant use case to check if following is NOT OK : - // - more than twice uses of the same variable - // - usage of the same variable on different kind of test statements (IF and ELSEIF) - public function shouldBeNotCompliantBecauseTheSameVariableIsUsedManyTimes() // NOT Compliant - { - $nb1 = 0; - $nb2 = 10; - $nb3 = 11; - - if ($nb1 == 1) { - $nb2 = 1; - } elseif ($nb1 == $nb2) { - $nb2 = 2; - } elseif ($nb3 == $nb1) { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb2 = 3; - } else { // NOK {{Use a switch statement instead of multiple if-else if possible}} - $nb2 = 4; - } - - return $nb2; - } - -} diff --git a/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php b/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php deleted file mode 100644 index 5a804bbdf..000000000 --- a/php-plugin/src/test/resources/checks/AvoidSQLRequestInLoop.php +++ /dev/null @@ -1,80 +0,0 @@ -query, $this->query, $this->query, $this->query, $this->query); - $this->init(); - $this->noLoop(); - $this->forLoop($expectedNbOfRequest, $someCondition); - $this->forEachLoop($arrayOfQuery, $someCondition); - $this->whileLoop($expectedNbOfRequest, $someCondition); - $this->emptyLoop(); - } - private function init() - { - $this->connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("Unable to Connect to '$dbhost'"); - mysql_select_db($this->dbName) or die("Could not open the db '$this->dbName'"); - } - - private function noLoop() - { - $result = mysql_query($this->query); - echo $result; - } - - private function forLoop($expectedNbOfRequest, $someCondition) - { - for ($index = 0; $expectedNbOfRequest > $index; ++$index) { - $result = mysql_query($this->query); // NOK {{Avoid SQL request in loop}} - - if ($someCondition) { - $result = mysql_query($this->otherQuery); // NOK {{Avoid SQL request in loop}} - } - - echo $result; - } - } - - private function forEachLoop($arrayOfQuery, $someCondition) - { - foreach ($arrayOfQuery as $query) { - $result = mysql_query($query); // NOK {{Avoid SQL request in loop}} - - if ($someCondition) { - $result = mysql_query($this->otherQuery); // NOK {{Avoid SQL request in loop}} - } - - echo $result; - } - } - - private function whileLoop($expectedNbOfRequest, $someCondition) - { - $nbOfRequest = 0; - do { - $result = mysql_query($this->query); // NOK {{Avoid SQL request in loop}} - - if($someCondition) { - $result = mysql_query($this->otherQuery); // NOK {{Avoid SQL request in loop}} - } - - echo $result; - ++$nbOfRequest; - } while ($expectedNbOfRequest > $nbOfRequest); - } - - private function emptyLoop() - { - for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); - } -} diff --git a/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php b/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php deleted file mode 100644 index f10a79842..000000000 --- a/php-plugin/src/test/resources/checks/AvoidTryCatchFinallyCheck_NOK_FailsAllTryStatements.php +++ /dev/null @@ -1,37 +0,0 @@ -getMessage(); -} - -try { // NOK {{Avoid using try-catch}} - throw new SpecificException("Hello"); -} catch (SpecificException $e) { - echo $e->getMessage() . " catch in\n"; -} finally { - echo $e->getMessage() . " finally \n"; -} - -try { // NOK {{Avoid using try-catch}} - throw new \Exception("Hello"); -} catch (\Exception $e) { - echo $e->getMessage() . " catch in\n"; -} diff --git a/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php b/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php deleted file mode 100644 index 3431ab82e..000000000 --- a/php-plugin/src/test/resources/checks/AvoidUsingGlobalVariablesCheck.php +++ /dev/null @@ -1,28 +0,0 @@ - 10) { - break; - } - echo $i; -} - -/* exemple 3 */ - -$i = 1; -for (; ;) { - if ($i > 10) { - break; - } - echo $i; - $i++; -} - -/* exemple 4 */ - -for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); // NOK {{Do not call a function in for-type loop declaration}} - - -function somewhat_calcMax() -{ - return 500; -} - - -for ($i = 0; $i <= somewhat_calcMax(); $i++) { // NOK {{Do not call a function in for-type loop declaration}} - var_dump($i); -} - -$maxI = somewhat_calcMax(); -for ($i = 0; $i <= $maxI; $i++) { // COMPLIANT - var_dump($i); -} diff --git a/php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php b/php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php deleted file mode 100644 index b63555ec7..000000000 --- a/php-plugin/src/test/resources/checks/UseOfMethodsForBasicOperations.php +++ /dev/null @@ -1,18 +0,0 @@ -io.ecocode ecocode-parent - 1.3.2-SNAPSHOT + 1.4.0-SNAPSHOT pom ecoCode Sonar Plugins Project @@ -80,7 +80,6 @@ ecocode-rules-specifications java-plugin - php-plugin @@ -109,7 +108,6 @@ 9.4.0.54424 7.19.0.31550 - 3.29.0.9684 2.5.0.1358 @@ -157,15 +155,6 @@ provided - - - org.sonarsource.php - sonar-php-plugin - ${sonarphp.version} - sonar-plugin - provided - - org.sonarsource.java From 4ec8f3c2a1c4245068b2596706be09f7b65081b1 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 8 Aug 2023 22:39:30 +0200 Subject: [PATCH 152/170] [ISSUE 205] Add compatibility with SonarQube 10.1 --- CHANGELOG.md | 2 ++ Dockerfile | 2 +- docker-compose.yml | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a5dd33f9..df047b034 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- [#205](https://github.com/green-code-initiative/ecoCode/issues/205) compatibility with SonarQube 10.1 + ### Changed ### Deleted diff --git a/Dockerfile b/Dockerfile index bd5462ffb..4233f483c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,5 +5,5 @@ COPY . /usr/src/ecocode WORKDIR /usr/src/ecocode RUN ./tool_build.sh -FROM sonarqube:10.0.0-community +FROM sonarqube:10.1.0-community COPY --from=builder /usr/src/ecocode/lib/* /opt/sonarqube/extensions/plugins/ diff --git a/docker-compose.yml b/docker-compose.yml index fb4d7bdda..35117b491 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,7 +1,7 @@ version: "3.3" services: sonar: - image: sonarqube:10.0.0-community + image: sonarqube:10.1.0-community container_name: sonar_ecocode ports: - "9000:9000" From 2b0dd3689119effa39f103df9dff9739df73f270 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 8 Aug 2023 22:45:05 +0200 Subject: [PATCH 153/170] upgrade CHANGELOG --- CHANGELOG.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df047b034..7c4b3ae36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - [#205](https://github.com/green-code-initiative/ecoCode/issues/205) compatibility with SonarQube 10.1 - -### Changed +- [#210](https://github.com/green-code-initiative/ecoCode/pull/210) Publish to Maven Central (module ecocode-rules-specifications) ### Deleted From 7237fd12bbd667646db990c39446e40af3b1cb8d Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 8 Aug 2023 22:47:06 +0200 Subject: [PATCH 154/170] upgrade CHANGELOG.md for next release 1.4.0 --- CHANGELOG.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c4b3ae36..5c24abca7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +### Changed + +### Deleted + +## [1.4.0] - 2023-08-08 + +### Added + - [#205](https://github.com/green-code-initiative/ecoCode/issues/205) compatibility with SonarQube 10.1 - [#210](https://github.com/green-code-initiative/ecoCode/pull/210) Publish to Maven Central (module ecocode-rules-specifications) @@ -157,7 +165,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - First official release of ecocode plugins : java plugin, php plugin and python plugin -[unreleased]: https://github.com/green-code-initiative/ecoCode/compare/v1.3.1...HEAD +[unreleased]: https://github.com/green-code-initiative/ecoCode/compare/v1.4.0...HEAD + +[1.4.0]: https://github.com/green-code-initiative/ecoCode/compare/v1.3.1...v1.4.0 [1.3.1]: https://github.com/green-code-initiative/ecoCode/compare/v1.3.0...v1.3.1 From 82e8dc9fdeba36f8eebd4c85e340e27325d51acb Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 8 Aug 2023 22:47:36 +0200 Subject: [PATCH 155/170] [maven-release-plugin] prepare release 1.4.0 --- ecocode-rules-specifications/pom.xml | 2 +- java-plugin/pom.xml | 2 +- pom.xml | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ecocode-rules-specifications/pom.xml b/ecocode-rules-specifications/pom.xml index ae208fe29..f8ece2d3a 100644 --- a/ecocode-rules-specifications/pom.xml +++ b/ecocode-rules-specifications/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.4.0-SNAPSHOT + 1.4.0 ecocode-rules-specifications diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index 1bbc76ddb..80a6d240e 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.4.0-SNAPSHOT + 1.4.0 ecocode-java-plugin diff --git a/pom.xml b/pom.xml index f9226df4d..af819b35e 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ io.ecocode ecocode-parent - 1.4.0-SNAPSHOT + 1.4.0 pom ecoCode Sonar Plugins Project @@ -86,7 +86,7 @@ scm:git:https://github.com/green-code-initiative/ecocode scm:git:https://github.com/green-code-initiative/ecocode https://github.com/green-code-initiative/ecocode - HEAD + 1.4.0 GitHub From 30933bff78c814a53fd043ae71a6986e59903012 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 8 Aug 2023 22:47:36 +0200 Subject: [PATCH 156/170] [maven-release-plugin] prepare for next development iteration --- ecocode-rules-specifications/pom.xml | 2 +- java-plugin/pom.xml | 2 +- pom.xml | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ecocode-rules-specifications/pom.xml b/ecocode-rules-specifications/pom.xml index f8ece2d3a..81977d3d7 100644 --- a/ecocode-rules-specifications/pom.xml +++ b/ecocode-rules-specifications/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.4.0 + 1.4.1-SNAPSHOT ecocode-rules-specifications diff --git a/java-plugin/pom.xml b/java-plugin/pom.xml index 80a6d240e..f5f780e25 100644 --- a/java-plugin/pom.xml +++ b/java-plugin/pom.xml @@ -5,7 +5,7 @@ io.ecocode ecocode-parent - 1.4.0 + 1.4.1-SNAPSHOT ecocode-java-plugin diff --git a/pom.xml b/pom.xml index af819b35e..45989d064 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ io.ecocode ecocode-parent - 1.4.0 + 1.4.1-SNAPSHOT pom ecoCode Sonar Plugins Project @@ -86,7 +86,7 @@ scm:git:https://github.com/green-code-initiative/ecocode scm:git:https://github.com/green-code-initiative/ecocode https://github.com/green-code-initiative/ecocode - 1.4.0 + HEAD GitHub From 51056b23e0601ab5068c1df6307087d68165d4ff Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 8 Aug 2023 23:00:28 +0200 Subject: [PATCH 157/170] update docker-compose for next snapshot --- docker-compose.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 35117b491..224b2fe21 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,8 +16,8 @@ services: SONAR_ES_BOOTSTRAP_CHECKS_DISABLE: 'true' volumes: - type: bind - source: ./java-plugin/target/ecocode-java-plugin-1.4.0-SNAPSHOT.jar - target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.4.0-SNAPSHOT.jar + source: ./java-plugin/target/ecocode-java-plugin-1.4.1-SNAPSHOT.jar + target: /opt/sonarqube/extensions/plugins/ecocode-java-plugin-1.4.1-SNAPSHOT.jar - "extensions:/opt/sonarqube/extensions" - "logs:/opt/sonarqube/logs" - "data:/opt/sonarqube/data" From f324104743a60e7bcc921942d6393caec48364eb Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 15 Aug 2023 23:35:02 +0200 Subject: [PATCH 158/170] [ISSUE 216] upgrade EC2 rule pour Java (multiple If/Else/Elseif) --- CHANGELOG.md | 2 + .../checks/AvoidMultipleIfElseStatement.java | 338 ++++++++++++++++-- .../files/AvoidMultipleIfElseStatement.java | 266 +++++++++++++- .../AvoidMultipleIfElseStatementNoIssue.java | 187 +++++++++- 4 files changed, 724 insertions(+), 69 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c24abca7..ed198779c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +-[#216](https://github.com/green-code-initiative/ecoCode/issues/216) EC2 [Java]: Multiple if-else statement improvment + ### Deleted ## [1.4.0] - 2023-08-08 diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java index 9460642ab..4cf870ea2 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java @@ -1,67 +1,329 @@ package fr.greencodeinitiative.java.checks; -import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; +import org.sonar.plugins.java.api.tree.BinaryExpressionTree; import org.sonar.plugins.java.api.tree.BlockTree; +import org.sonar.plugins.java.api.tree.ExpressionTree; +import org.sonar.plugins.java.api.tree.IdentifierTree; import org.sonar.plugins.java.api.tree.IfStatementTree; +import org.sonar.plugins.java.api.tree.MethodTree; import org.sonar.plugins.java.api.tree.StatementTree; import org.sonar.plugins.java.api.tree.Tree; +import org.sonar.plugins.java.api.tree.Tree.Kind; import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; +/** + * FUNCTIONAL DESCRIPTION : please see ASCIIDOC description file of this rule (inside `ecocode-rules-spcifications`) + * TECHNICAL CHOICES : + * - Kind.IF_STATEMENT, Kind.ELSE_STATEMENT, Kind.ELSEIF_STATEMENT not used because it isn't possible + * to keep parent references to check later if variables already used or not in parent tree + * - only one way to keep parent history : manually go throw the all tree and thus, start at method declaration + * - an "ELSE" statement is considered as a second IF statement using the same variables used on previous + * - IF and ELSEIF statements are considered as an IF statement + */ @Rule(key = "EC2") @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "AMIES") public class AvoidMultipleIfElseStatement extends IssuableSubscriptionVisitor { - protected static final String RULE_MESSAGE = "Using a switch statement instead of multiple if-else if possible"; - private void checkIfStatement(Tree tree) { - int sizeBody = 0; - int idx = 0; - int countIfStatement = 0; + public static final String ERROR_MESSAGE = "Use a switch statement instead of multiple if-else if possible"; - Tree parentNode = tree.parent(); + public static final int NB_MAX_VARIABLE_USAGE = 2; - if (!(parentNode instanceof BlockTree)) + // data structure for following usage of variable inside all the AST tree + private VariablesPerLevelDataStructure variablesStruct = new VariablesPerLevelDataStructure(); + + // only visit each method to keep data of all conditional tree + // with IF, ELSE or ELSEIF statements, we can't keep all data of conditional tree + @Override + public List nodesToVisit() { + return List.of(Kind.METHOD); + } + + @Override + public void visitNode(@SuppressWarnings("NullableProblems") Tree pTree) { + + MethodTree method = (MethodTree)pTree; + + // reinit data structure before each method analysis + variablesStruct = new VariablesPerLevelDataStructure(); + + // starting visit + visitNodeContent(method.block().body(), 0); + + } + + /** + * Visit all content of a node for one level (with its statements list) + * + * @param pLstStatements statements list of current node + * @param pLevel level of current node + */ + private void visitNodeContent(List pLstStatements, int pLevel) { + if (pLstStatements == null || pLstStatements.isEmpty()) { return; - BlockTree node = (BlockTree) parentNode; - sizeBody = node.body().toArray().length; - while (idx < sizeBody) { - if (node.body().get(idx) instanceof IfStatementTree) - ++countIfStatement; - ++idx; - } - if (countIfStatement > 1) - reportIssue(tree, RULE_MESSAGE); + } + + for (StatementTree statement : pLstStatements) { + if (statement.is(Kind.BLOCK)) { + // the current node is a block : visit block content + visitNodeContent(((BlockTree)statement).body(), pLevel); + } else if (statement.is(Kind.IF_STATEMENT)) { + visitIfNode((IfStatementTree) statement, pLevel); + } + } } - private void checkElseIfStatement(Tree tree) { - IfStatementTree node = (IfStatementTree) tree; - int count = 0; - StatementTree statementTree; - - while (true) { - if (count >= 2) - reportIssue(tree, RULE_MESSAGE); - statementTree = node.elseStatement(); - if (statementTree instanceof IfStatementTree) { - ++count; - node = (IfStatementTree) statementTree; - } else { - break; + /** + * Visit an IF type node + * @param pIfTree the current node (Tree type) + * @param pLevel the level of node + */ + private void visitIfNode(IfStatementTree pIfTree, int pLevel) { + + if (pIfTree == null) return; + + // init current if structure with cleaning child levels + variablesStruct.reinitVariableUsageForLevel(pLevel + 1); + // init current if structure with cleaning for ELSE process checking + variablesStruct.reinitVariableUsageForLevelForCurrentIfStruct(pLevel); + + // analyze condition variables and raise error if needed + computeIfVariables(pIfTree, pLevel); + + // visit the content of if block + visitNodeContent(((BlockTree)pIfTree.thenStatement()).body(), pLevel + 1); + + // analyze ELSE clause et ELSE IF clauses + if (pIfTree.elseStatement() != null) { + if (pIfTree.elseStatement().is(Kind.BLOCK)) { // ELSE clause content + visitElseNode((BlockTree) pIfTree.elseStatement(), pLevel); + } else if (pIfTree.elseStatement().is(Kind.IF_STATEMENT)) { // ELSE IF clause + visitIfNode((IfStatementTree) pIfTree.elseStatement(), pLevel); } } } - @Override - public List nodesToVisit() { - return Arrays.asList(Tree.Kind.IF_STATEMENT); + /** + * Analyze and compute variables usage for IF AST structure + * @param pIfTree IF node + * @param pLevel the level of IF node + */ + private void computeIfVariables(IfStatementTree pIfTree, int pLevel) { + + if (pIfTree.condition() == null) return; + + // analysing content of conditions of IF node + ExpressionTree expr = pIfTree.condition(); + if (expr instanceof BinaryExpressionTree) { + computeConditionVariables((BinaryExpressionTree) expr, pLevel); + } + } - @Override - public void visitNode(Tree tree) { - checkIfStatement(tree); - checkElseIfStatement(tree); + /** + * Analyze and compute variables usage for Expression structure + * @param pBinExprTree binary expression to analyze + * @param pLevel The level of binary expression + */ + private void computeConditionVariables(BinaryExpressionTree pBinExprTree, int pLevel) { + + // if multiple conditions, continue with each part of complex expression + if (pBinExprTree.is(Kind.CONDITIONAL_AND) || pBinExprTree.is(Kind.CONDITIONAL_OR)) { + if (pBinExprTree.leftOperand() instanceof BinaryExpressionTree) { + computeConditionVariables((BinaryExpressionTree) pBinExprTree.leftOperand(), pLevel); + } + if (pBinExprTree.rightOperand() instanceof BinaryExpressionTree) { + computeConditionVariables((BinaryExpressionTree) pBinExprTree.rightOperand(), pLevel); + } + } else if (pBinExprTree.is(Kind.EQUAL_TO) + || pBinExprTree.is(Kind.NOT_EQUAL_TO) + || pBinExprTree.is(Kind.GREATER_THAN) + || pBinExprTree.is(Kind.GREATER_THAN_OR_EQUAL_TO) + || pBinExprTree.is(Kind.LESS_THAN_OR_EQUAL_TO) + || pBinExprTree.is(Kind.LESS_THAN) + ) { + // continue analysis with variables if some key-words are found + if (pBinExprTree.leftOperand().is(Kind.IDENTIFIER)) { + computeVariables((IdentifierTree) pBinExprTree.leftOperand(), pLevel); + } + if (pBinExprTree.rightOperand().is(Kind.IDENTIFIER)) { + computeVariables((IdentifierTree) pBinExprTree.rightOperand(), pLevel); + } + } + } + + /** + * Analyze and compute variables usage for Variable AST structure + * @param pVarIdTree The Variable AST structure + * @param pLevel the level of structure + */ + private void computeVariables(IdentifierTree pVarIdTree, int pLevel) { + if (pVarIdTree.is(Kind.IDENTIFIER)) { + // increment the variable counter to list of all variables + int nbUsed = variablesStruct.incrementVariableUsageForLevel(pVarIdTree.name(), pLevel); + + // increment variable counter to list of variables already declared for current if or elseif struture + variablesStruct.incrementVariableUsageForLevelForCurrentIfStruct(pVarIdTree.name(), pLevel); + + // raise an error if maximum + if (nbUsed > NB_MAX_VARIABLE_USAGE) { + reportIssue(pVarIdTree, ERROR_MESSAGE); + } + } + } + + /** + * Analyze and compute variables usage for ELSE AST structure + * @param pElseTree ELSE node + * @param pLevel the level of ELSE node + */ + private void visitElseNode(BlockTree pElseTree, int pLevel) { + + if (pElseTree == null) { return; } + + // analyze variables and raise error if needed + computeElseVariables(pElseTree, pLevel); + + // go to next child level + visitNodeContent(pElseTree.body(), pLevel + 1); } + + /** + * Analyze and compute variables usage for ELSE AST structure + * @param pElseTree ELSE node + * @param pLevel the level of ELSE node + */ + private void computeElseVariables(StatementTree pElseTree, int pLevel) { + + for (Map.Entry entry : variablesStruct.getVariablesForCurrentIfStruct(pLevel).entrySet()) { + String variableName = entry.getKey(); + + // increment usage of all variables in the same level of ELSE staetement + int nbUsed = variablesStruct.incrementVariableUsageForLevel(variableName, pLevel); + + // increment variable counter to list of variables already declared for current if or elseif struture + variablesStruct.incrementVariableUsageForLevelForCurrentIfStruct(variableName, pLevel); + + // raise an error if maximum + if (nbUsed > NB_MAX_VARIABLE_USAGE) { + reportIssue(pElseTree, ERROR_MESSAGE); + } + } + } + + /** + * Complex data structure representing variables counters per AST level (cumulative counts with parent levels) + * Map> ==> + * - Key : index of Level (0 = first level) + * - Value : Map + * - Key : name of variable in the current or parent level + * - Value : number of usage of this variable in an IF statement in current level or one of parent levels + * + */ + private static class VariablesPerLevelDataStructure { + + // global map variable counters per level + private final Map> mapVariablesPerLevel; + + // map variable counters per level for current If / ElseIf structure + // purpose : used by compute variables Else process (because Else structure is particular : + // we don't know previous variables and we need previous If / ElseIf structure to know variables) + private final Map> mapVariablesPerLevelForCurrentIfStruct; + + public VariablesPerLevelDataStructure() { + mapVariablesPerLevel = new HashMap<>(10); + mapVariablesPerLevelForCurrentIfStruct = new HashMap<>(10); + } + + /** + * increment variable counters on global map + */ + public int incrementVariableUsageForLevel(String variableName, int pLevel) { + return internalIncrementVariableUsage(mapVariablesPerLevel, variableName, pLevel); + } + + /** + * increment variable counters on input map + */ + private int internalIncrementVariableUsage(Map> pDataMap, String variableName, int pLevel) { + + // get variable usage map for current level and init if null + Map variablesMap = pDataMap.computeIfAbsent(pLevel, k -> new HashMap<>(5)); + + // get usage from parent if needed + Integer nbUsed = variablesMap.get(variableName); + if (nbUsed == null) { + Integer nbParentUsed = internalGetVariableUsageOfNearestParent(pDataMap, variableName, pLevel - 1); + nbUsed = nbParentUsed == null ? 0 : nbParentUsed; + } + + // increment usage for current level + nbUsed++; + variablesMap.put(variableName, nbUsed); + + return nbUsed; + } + + /** + * get usage of a variable in top tree (nearest top parent) + */ + private Integer internalGetVariableUsageOfNearestParent(Map> pDataMap, String variableName, int pLevel) { + + Integer nbParentUsed = null; + for (int i = pLevel; i >= 0 && nbParentUsed == null; i--) { + Map variablesParentLevelMap = pDataMap.get(i); + nbParentUsed = variablesParentLevelMap.get(variableName); + } + + return nbParentUsed; + } + + /** + * reinitialization of variable usages for input level and global map + */ + public void reinitVariableUsageForLevel(int pLevel) { + internalReinitVariableUsageForLevelForCurrentIfStruct(mapVariablesPerLevel, pLevel); + } + + /** + * reinitialization of variable usages in input level in input map + */ + private void internalReinitVariableUsageForLevelForCurrentIfStruct(Map> pDataMap, int pLevel) { + if (pDataMap.get(pLevel) == null) { return; } + + // cleaning of current If Structure beginning at level specified + for (int i = pLevel; i < pDataMap.size(); i++) { + pDataMap.remove(i); + } + + } + + /** + * reinitialization of variable usages for input level on if/elseif map + */ + public void reinitVariableUsageForLevelForCurrentIfStruct(int pLevel) { + internalReinitVariableUsageForLevelForCurrentIfStruct(mapVariablesPerLevelForCurrentIfStruct, pLevel); + } + + /** + * increment variable counters on if/elseif map + */ + public void incrementVariableUsageForLevelForCurrentIfStruct(String variableName, int pLevel) { + internalIncrementVariableUsage(mapVariablesPerLevelForCurrentIfStruct, variableName, pLevel); + } + + /** + * get usage of a variable in a level on if/elseif map + */ + public Map getVariablesForCurrentIfStruct(int pLevel) { + return mapVariablesPerLevelForCurrentIfStruct.get(pLevel); + } + + } + } diff --git a/java-plugin/src/test/files/AvoidMultipleIfElseStatement.java b/java-plugin/src/test/files/AvoidMultipleIfElseStatement.java index 88e40ad0c..1b3b9fc96 100644 --- a/java-plugin/src/test/files/AvoidMultipleIfElseStatement.java +++ b/java-plugin/src/test/files/AvoidMultipleIfElseStatement.java @@ -1,38 +1,266 @@ package fr.greencodeinitiative.java.checks; class AvoidMultipleIfElseStatementCheck { - AvoidMultipleIfElseStatementCheck(AvoidMultipleIfElseStatementCheck mc) { + +// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// // +// // NON COMPLIANT use cases +// // +// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + // NON COMPLIANT + // USE CASE : Non compliant use case to check if following is NON OK : + // - two uses of the same variable + // - usage of the same variable on different levels of IF statements + public int shouldBeCompliantBecauseVariableUsedMaximumTwiceInComposedElseStatements() + { + int nb1 = 0; + + if (nb1 == 1) { + nb1 = 2; + } else { + if (nb1 == 2) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 1; + } + } + + return nb1; } - public void methodWithMultipleIfElseIf() { + // NON COMPLIANT + // USE CASE : non compliant use case to check if a variable is not used max twice on several IF / ELSE statements + // at the same level + public int shouldBeNotCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsed() + { int nb1 = 0; - int nb2 = 10; + int nb2 = 0; + int nb3 = 0; - if (nb1 == 1) { // Noncompliant {{Using a switch statement instead of multiple if-else if possible}} + if (nb3 == 1 + && nb3 == 2 + && nb3 == 3) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} nb1 = 1; - } else if (nb1 == nb2) { - // - } else if (nb2 == nb1) { - // + } else { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb2 = 2; + } + + if (nb2 == 2) { + nb1 = 3; } else { - // + nb1 = 4; } - nb1 = nb2; + + return nb1; } - public void methodWithMultipleIfElse() { + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT COMPLIANT : + // one variable is used maximum in two IF / ELSE / ELSEIF statements + public int shouldBeNotCompliantBecauseVariablesIsUsedMoreThanTwice() + { int nb1 = 0; - int nb2 = 10; - if (nb1 == 1) { // Noncompliant {{Using a switch statement instead of multiple if-else if possible}} - nb1 = 1; + if (nb1 == 1) { + nb1 = 2; } else { - // + nb1 = 3; } - if (nb1 == 1) { // Noncompliant {{Using a switch statement instead of multiple if-else if possible}} - nb1 = 1; + + if (nb1 == 2) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 4; + } + + return nb1; + } + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT OK : + // - same variable used maximum twice : no compliant because 2 IFs and 1 ELSE + public int shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInIfStatementsAtDifferentsLevels() + { + int nb1 = 0; + + if (nb1 == 1) { + if (nb1 == 2) { + nb1 = 1; + } else { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 3; + } } else { - // + nb1 = 2; } + + return nb1; + } + + + // NON COMPLIANT + // USE CASE : non compliant use case to check if following is NOT OK : + // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE + // - usage of the same variable on different levels of IF statements + public int shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatements() + { + int nb1 = 0; + + if (nb1 == 1) { + nb1 = 2; + } else { + if (nb1 == 2) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 1; + } else { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 3; + } + } + + return nb1; + } + + // NON COMPLIANT + // USE CASE : non compliant use case to check if following is NOT OK : + // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE + // - usage of the same variable on different levels of IF statements + public int shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatementsScenario2() + { + int nb1 = 0; + + if (nb1 == 1) { + if (nb1 == 3) { + nb1 = 4; + } else { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 5; + } + } else { + if (nb1 == 2) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 1; + } else { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 3; + } + } + + return nb1; } -} \ No newline at end of file + + + // NON COMPLIANT + // USE CASE : non compliant use case to check if following is NOT OK : + // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE + // - usage of the same variable on different levels of IF statements + public int shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatementsScenario3() + { + int nb1 = 0; + int nb2 = 0; + + if (nb1 == 1) { + if (nb1 == 3) { + nb1 = 4; + } else { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 5; + } + } else if (nb2 == 2) { + if (nb1 == 4) { + nb1 = 5; + } else { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 6; + } + } + + return nb1; + } + + // NON COMPLIANT + // USE CASE : non compliant use case to check if following is NOT OK : + // - two uses of the same variable : use thre times with 2 IFs and 1 ELSE + // - usage of the same variable on different levels of IF statements + public int shouldBeNotCompliantBecauseVariableUsedMoreThanTwiceInComposedElseStatementsScenario4() + { + int nb1 = 0; + int nb2 = 0; + + if (nb1 == 1) { + if (nb2 == 3) { + nb1 = 4; + } else { + nb1 = 5; + } + } else if (nb2 == 2) { + if (nb1 == 3) { + nb1 = 4; + } else { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 5; + } + } + + return nb1; + } + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT OK : + // - the same variable must used maximum twice + // - usage of the same variable on different levels of IF / ELSE statements + public int shouldBeNotCompliantBecauseVariableUsedMaximumTwiceInComposedElseStatements() + { + int nb1 = 0; + + if (nb1 == 1) { + nb1 = 2; + } else { + if (nb1 == 2) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 1; + } else { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + if (nb1 == 3) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 4; + } else { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb1 = 5; + } + } + } + + return nb1; + } + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT OK : + // - more than twice uses of the same variable + // - usage of the same variable on different kind of test statements (IF and ELSEIF) + public int shouldBeNotCompliantBecauseTheSameVariableIsUsedMoreThanTwice() // NOT Compliant + { + int nb1 = 0; + int nb2 = 10; + + if (nb1 == 1) { + nb2 = 1; + } else if (nb1 == nb2) { + nb2 = 2; + } else { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb2 = 4; + } + + return nb2; + } + + // NON COMPLIANT + // USE CASE : NON compliant use case to check if following is NOT OK : + // - more than twice uses of the same variable + // - usage of the same variable on different kind of test statements (IF and ELSEIF) + public int shouldBeNotCompliantBecauseTheSameVariableIsUsedManyTimes() // NOT Compliant + { + int nb1 = 0; + int nb2 = 10; + int nb3 = 11; + + if (nb1 == 1) { + nb2 = 1; + } else if (nb1 == nb2) { + nb2 = 2; + } else if (nb3 == nb1) { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb2 = 3; + } else { // Noncompliant {{Use a switch statement instead of multiple if-else if possible}} + nb2 = 4; + } + + return nb2; + } + +} diff --git a/java-plugin/src/test/files/AvoidMultipleIfElseStatementNoIssue.java b/java-plugin/src/test/files/AvoidMultipleIfElseStatementNoIssue.java index 60d10293c..d3a57b7a6 100644 --- a/java-plugin/src/test/files/AvoidMultipleIfElseStatementNoIssue.java +++ b/java-plugin/src/test/files/AvoidMultipleIfElseStatementNoIssue.java @@ -1,31 +1,194 @@ package fr.greencodeinitiative.java.checks; -class AvoidMultipleIfElseStatementNoIssueCheck { - AvoidMultipleIfElseStatementNoIssueCheck(AvoidMultipleIfElseStatementNoIssueCheck mc) { +class AvoidMultipleIfElseStatementCheckNoIssue { + + // inital RULES : please see HTML description file of this rule (resources directory) + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // + // COMPLIANT use cases + // + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + // COMPLIANT + // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements + // at the same level AND no problem with several IF staments at the same level using different variables + public int shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsed() + { + int nb1 = 0; + int nb2 = 0; + int nb3 = 0; + + if (nb3 != 1 && nb1 > 1) { + nb1 = 1; + } else { + nb2 = 2; + } + + if (nb2 == 2) { + nb1 = 3; + } else { + nb1 = 4; + } + + return nb1; } - public void methodWithOneIfElseIf() { + // COMPLIANT + // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements + // at the same level AND no problem with several IF staments at the same level using different variables + public int shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDifferentsVariablesUsedAtDiffLevels() + { + int nb1 = 0; + int nb2 = 0; + int nb3 = 0; + + if (nb1 < 1) { + if (nb2 == 2) { + nb3 = 3; + } else { + nb3 = 4; + } + } else { + nb2 = 2; + } + + if (nb3 >= 1) { + if (nb2 == 2) { + nb1 = 3; + } else { + nb1 = 4; + } + } else { + nb1 = 2; + } + + return nb1; + } + + // COMPLIANT + // USE CASE : compliant use case to check if a variable is used maximum twice on several IF / ELSE statements + // at the same level AND no problem with several IF staments at the same level using different variables + public int shouldBeCompliantBecauseVariablesUsedMaximumTwiceAndDiffVariablesUsedAtDiffLevelsScenario2() + { + int nb1 = 0; + int nb2 = 0; + int nb3 = 0; + + if (nb1 <= 1) { + if (nb2 == 2) { + if (nb3 == 2) { + nb3 = 3; + } else { + nb3 = 4; + } + } else { + nb3 = 4; + } + } else { + nb2 = 2; + } + + if (nb3 == 1) { + if (nb2 == 2) { + nb1 = 3; + } else { + nb1 = 4; + } + } else { + nb1 = 2; + } + + return nb1; + } + + // COMPLIANT + // USE CASE : compliant use case to check if one variable is used maximum twice in different IF statements + public int shouldBeCompliantBecauseVariableUsedMaximumTwiceInIfStatements() + { int nb1 = 0; - int nb2 = 10; if (nb1 == 1) { nb1 = 1; - } else if (nb1 == nb2) { - // + } + + if (nb1 == 2) { + nb1 = 3; + } + + return nb1; + } + + // COMPLIANT + // USE CASE : compliant use case to check if following is OK : + // - two uses of the same variable + // - usage of the same variable on different levels of IF statements + public int shouldBeCompliantBecauseSereralVariablesUsedMaximumTwiceInComposedElseStatements() + { + int nb1 = 0; + int nb2 = 0; + int nb3 = 0; + + if (nb1 == 1) { + nb1 = 2; } else { - // + if (nb2 == 2) { + nb1 = 1; + } else { + if (nb3 == 4) { + nb1 = 3; + } else { + nb1 = 6; + } + } } - nb1 = nb2; + + return nb1; } - public void methodWithOneIfElse() { + // COMPLIANT + // USE CASE : compliant use case to check if following is OK : + // - two uses of the same variable + // - usage of the same variable on different kind of test statements (IF and ELSEIF) + public int shouldBeCompliantBecauseVariableUsedMaximumTwiceInIfOrElseIfStatements() // Compliant + { int nb1 = 0; int nb2 = 10; if (nb1 == 1) { - nb1 = 1; + nb2 = 1; + } else if (nb1 == nb2) { + nb2 = 2; + } + + return nb2; + } + + // COMPLIANT + // USE CASE : compliant use case to check if following is OK : + // - two uses of the same variable + // - usage of the same variable on different kind of test statements (IF and ELSEIF) + public int shouldBeCompliantBecauseSeveralVariablesUsedMaximumTwiceInIfOrElseIfStatements() // Compliant + { + int nb1 = 0; + int nb2 = 10; + int nb3 = 3; + int nb4 = 1; + int nb5 = 2; + + if (nb1 == 1) { + nb2 = 1; + } else if (nb3 == nb2) { + nb2 = 2; + } else if (nb4 == nb5) { + nb2 = 4; } else { - // + nb2 = 3; } + + return nb2; } -} \ No newline at end of file + +} From bca1538450ce2bd4cbe873a76f75b315e9f111eb Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Tue, 15 Aug 2023 23:40:23 +0200 Subject: [PATCH 159/170] [ISSUE 216] upgrade EC2 rule pour Java (multiple If/Else/Elseif) - upgrade doc in ecocode-rules-specifications --- .../src/main/rules/EC2/java/EC2.asciidoc | 53 +++++++++++++------ 1 file changed, 38 insertions(+), 15 deletions(-) diff --git a/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc b/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc index 0e56f2845..df00a5933 100644 --- a/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc @@ -1,32 +1,55 @@ -If we are using too many conditional `if` – `else` statements it will impact performance since JVM will have to compare the conditions. We can think of using a switch statement instead of multiple `if` – `else` if possible. `switch` statement has a performance advantage over `if` – `else`. +If we are using too many conditional IF, ELSEIF or ELSE statements it will impact performance. +We can think of using a switch statement instead of multiple if-else if possible, or refactor code +to reduce number of IF, ELSEIF and ELSE statements. Sometimes called "complexity cyclomatic". +Switch statement has a performance advantage over if – else. + +## Functional rules +- one variable must be used maximum twice in IF / ELSEIF / ELSE statements at the same level - WARNINGs : +- IF and ELSEIF statements use explicitly variable names ! +- ELSE statements use implicity variable names ! +- one variable must be used maximum twice in IF / ELSEIF / ELSE statements at differents hierarchical levels +- we can assume that if one variable is used three times or more, we should : +- use a SWITCH statement instead +- or refactor the code if possible ## Non-compliant Code Example +NON compliant, because `nb` is used 4 times : +- 2 explicit times in IF statements +- 2 implicit times in ELSE statements + ```java int index = 1; int nb = 2; - -if (nb > index) { - nb = nb + index; -} else { - nb = nb - 1; -} -if (nb != index + 1) { - nb = nb + index; +... +if (nb == 0) { + nb = index; +} else if (nb == 1) { + nb = index * 2; +} else if (nb == 2) { + nb = index * 3; } else { - nb = nb - 1; + nb = -1; } +return nb; ``` ## Compliant Code Example +SWITCH statement solution + refactor solution + ```java int index = 1; int nb = 2; - -if (nb > index) { - nb = nb + index; -} else { - nb = nb - 1; +... +switch (nb) { + case 0: + case 1: + case 2: + nb = index * (nb + 1); + break; + default: + nb = -1; } +return nb; ``` From 25bdb8b9398d2ecc6251f3ba289e55b49ad0dae9 Mon Sep 17 00:00:00 2001 From: Maxime Malgorn <9255967+utarwyn@users.noreply.github.com> Date: Fri, 18 Aug 2023 01:17:40 +0200 Subject: [PATCH 160/170] Update README.md --- README.md | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 40b803849..4942fbea7 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ refer to the contribution section. - [Java](java-plugin/) - [JavaScript](https://github.com/green-code-initiative/ecoCode-javascript) -- [PHP](php-plugin/) +- [PHP](https://github.com/green-code-initiative/ecoCode-php) - [Python](https://github.com/green-code-initiative/ecoCode-python) ![Screenshot](docs/resources/screenshot.PNG) @@ -78,24 +78,26 @@ Ready to use binaries are available [from GitHub](https://github.com/green-code- | Plugins Version | SonarQube version | |------------------|-----------------------------| -| 0.1.+ | SonarQube 8.9.+ LTS to 9.3 | -| 0.2.+ | SonarQube 9.4.+ LTS to 9.9 | -| 1.0.+ | SonarQube 9.4.+ LTS to 9.9 | -| 1.1.+ | SonarQube 9.4.+ LTS to 9.9 | -| 1.2.+ | SonarQube 9.4.+ LTS to 10.0 | +| 1.4.+ | SonarQube 9.4.+ LTS to 10.1 | | 1.3.+ | SonarQube 9.4.+ LTS to 10.0 | +| 1.2.+ | SonarQube 9.4.+ LTS to 10.0 | +| 1.1.+ | SonarQube 9.4.+ LTS to 9.9 | +| 1.0.+ | SonarQube 9.4.+ LTS to 9.9 | +| 0.2.+ | SonarQube 9.4.+ LTS to 9.9 | +| 0.1.+ | SonarQube 8.9.+ LTS to 9.3 | ☕ Plugin Java part compatibility ------------------ | Plugins Version | Java version | |------------------|--------------| -| 0.1.+ | 11 / 17 | -| 0.2.+ | 11 / 17 | -| 1.0.+ | 11 / 17 | -| 1.1.+ | 11 / 17 | -| 1.2.+ | 11 / 17 | +| 1.4.+ | 11 / 17 | | 1.3.+ | 11 / 17 | +| 1.2.+ | 11 / 17 | +| 1.1.+ | 11 / 17 | +| 1.0.+ | 11 / 17 | +| 0.2.+ | 11 / 17 | +| 0.1.+ | 11 / 17 | 🤝 Contribution --------------- @@ -126,6 +128,7 @@ Then, if no answer, contact ... - [Olivier Le Goaër](https://olegoaer.perso.univ-pau.fr) - [Maxime DUBOIS](https://www.linkedin.com/in/maxime-dubois-%F0%9F%8C%B1-649a3a3/) - [David DE CARVALHO](https://www.linkedin.com/in/david%E2%80%8E-de-carvalho-8b395284/) +- [Maxime MALGORN](https://www.linkedin.com/in/maximemalgorn/) 🧐 Core Team Emeriti -------------------- From fdaac9098bada79f62c6186e2e4dd12c29b837f4 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 1 Sep 2023 16:43:12 +0200 Subject: [PATCH 161/170] [ISSUE 216] upgrade EC2 rule pour Java (multiple If/Else/Elseif) - upgrade CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed198779c..f4eac1818 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed --[#216](https://github.com/green-code-initiative/ecoCode/issues/216) EC2 [Java]: Multiple if-else statement improvment +-[#216](https://github.com/green-code-initiative/ecoCode/issues/216) Upgrade rule EC2 fro Java : Multiple if-else statement improvment ### Deleted From c2e2cbe8910691aa1fcf02e788385a2b5e4a7c0e Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 1 Sep 2023 17:09:33 +0200 Subject: [PATCH 162/170] [ISSUE 106] rule EC67 not relevant neither for python nor Rust --- RULES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RULES.md b/RULES.md index 3d03ed6d9..21f34dafa 100644 --- a/RULES.md +++ b/RULES.md @@ -31,7 +31,7 @@ Some are applicable for different technologies. | EC7 | Rewrite native getter/setters | Overloading them lengthens the compilation and execution times of these methods, which are usually much better optimized by the language than by the developer. | [cnumr best practices (3rd edition) BP_062 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | 🚀 | 🚀 | ✅ | 🚀 | | EC63 | Unnecessarily assigning values to variables | Avoid declaring and using variables when it is not indis-thinkable. Indeed, each allocation corresponds to the RAM occupied. | [cnumr best practices (3rd edition) BP_063 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | 🚀 | 🚀 | 🚀 | 🚀 | | EC66 | Use single quote (') instead of quotation mark (") | The shape using the quotation marks allows the developer to insert variables that will be substituted at run time. But if the string does not have a variable, use quotes instead. Thus, language will not look for variables to subtituture, which will reduce the consumption of CPU cycles. | [cnumr best practices (3rd edition) BP_066 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | ✅ | 🚀 | ✅ | 🚀 | -| EC67 | Use the $i++ variable during an iteration | The $i++ form has the disadvantage of generating a tem-porary variable during incrementation, which is not the case with the ++$i form. | [cnumr best practices (3rd edition) BP_067 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | 🚀 | 🚀 | +| EC67 | Use the $i++ variable during an iteration | The $i++ form has the disadvantage of generating a tem-porary variable during incrementation, which is not the case with the ++$i form. | [cnumr best practices (3rd edition) BP_067 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | 🚫 | 🚫 | | EC69 | Calling a function in the declaration of a for loop | Avoid calling the function each time the loop is iterated. | [cnumr best practices (3rd edition) BP_069 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | ✅ | 🚀 | | EC72 | Perform an SQL query inside a loop | Servers are optimized to process multiple selections, insertions, or changes in a single query or transaction. consume CPU cycles, RAM, and bandwidth unnecessarily. | [cnumr best practices (3rd edition) BP_072](https://github.com/cnumr/best-practices/blob/main/chapters/BP_072_fr.md) | ✅ | ✅ | 🚀 | ✅ | 🚀 | | EC74 | Write SELECT * FROM | The database server must resolve the fields based on the schema. If you are familiar with the diagram, it is strongly recommended to name the fields. | [cnumr best practices (3rd edition) BP_074 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | ✅ | 🚀 | From 27bab5e37aea6425ae55802d32a61ecbf80732e5 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 1 Sep 2023 17:12:30 +0200 Subject: [PATCH 163/170] [ISSUE 106] rule EC67 not relevant neither for python nor Rust - upgrade CHANGELOG.md --- CHANGELOG.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f4eac1818..e72c5e3da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -### Added - ### Changed --[#216](https://github.com/green-code-initiative/ecoCode/issues/216) Upgrade rule EC2 fro Java : Multiple if-else statement improvment +-[#216](https://github.com/green-code-initiative/ecoCode/issues/216) Upgrade rule EC2 for Java : Multiple if-else statement improvment +-[#106](https://github.com/green-code-initiative/ecoCode/issues/106) Upgrade RULES.md : rule EC67 not relevant neither for Python nor Rust ### Deleted From 30dc28b60c9c8b539d66eb39e447e4960790e715 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 8 Sep 2023 10:35:48 +0200 Subject: [PATCH 164/170] Update CHANGELOG.md --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e72c5e3da..5417e622f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed --[#216](https://github.com/green-code-initiative/ecoCode/issues/216) Upgrade rule EC2 for Java : Multiple if-else statement improvment --[#106](https://github.com/green-code-initiative/ecoCode/issues/106) Upgrade RULES.md : rule EC67 not relevant neither for Python nor Rust +- [#216](https://github.com/green-code-initiative/ecoCode/issues/216) Upgrade rule EC2 for Java : Multiple if-else statement improvment +- [#106](https://github.com/green-code-initiative/ecoCode/issues/106) Upgrade RULES.md : rule EC67 not relevant neither for Python nor Rust ### Deleted From 1ac339d27f14bc78b3af14192d1f67ac3a5943f5 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 15 Sep 2023 10:47:50 +0200 Subject: [PATCH 165/170] move enum to another package --- .../java/checks/AvoidSetConstantInBatchUpdate.java | 3 ++- .../java/checks/{ => enums}/ConstOrLiteralDeclare.java | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) rename java-plugin/src/main/java/fr/greencodeinitiative/java/checks/{ => enums}/ConstOrLiteralDeclare.java (98%) diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java index 4a014c2a3..06e63179b 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java @@ -4,7 +4,8 @@ import java.util.List; import java.util.stream.Stream; -import static fr.greencodeinitiative.java.checks.ConstOrLiteralDeclare.isLiteral; +import fr.greencodeinitiative.java.checks.enums.ConstOrLiteralDeclare; +import static fr.greencodeinitiative.java.checks.enums.ConstOrLiteralDeclare.isLiteral; import static java.util.Arrays.asList; import org.sonar.check.Rule; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ConstOrLiteralDeclare.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/enums/ConstOrLiteralDeclare.java similarity index 98% rename from java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ConstOrLiteralDeclare.java rename to java-plugin/src/main/java/fr/greencodeinitiative/java/checks/enums/ConstOrLiteralDeclare.java index 8a5b459a0..f6ece9e7b 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ConstOrLiteralDeclare.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/enums/ConstOrLiteralDeclare.java @@ -1,4 +1,4 @@ -package fr.greencodeinitiative.java.checks; +package fr.greencodeinitiative.java.checks.enums; import java.math.BigDecimal; import java.util.Set; @@ -18,7 +18,7 @@ import static org.sonar.plugins.java.api.tree.Tree.Kind.TYPE_CAST; import org.sonar.plugins.java.api.tree.TypeCastTree; -enum ConstOrLiteralDeclare { +public enum ConstOrLiteralDeclare { BOOLEAN { @Override From d89e2a2226c02e56eddbdb1bf3617cd5612caee7 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 15 Sep 2023 11:32:38 +0200 Subject: [PATCH 166/170] refacto - upgrade licences --- .../java/JavaCheckRegistrar.java | 15 ++++----- .../greencodeinitiative/java/JavaPlugin.java | 15 ++++----- .../java/JavaRulesDefinition.java | 15 ++++----- .../java/checks/ArrayCopyCheck.java | 17 ++++++++++ .../checks/AvoidConcatenateStringsInLoop.java | 17 ++++++++++ .../java/checks/AvoidFullSQLRequest.java | 17 ++++++++++ .../AvoidGettingSizeCollectionInLoop.java | 17 ++++++++++ .../checks/AvoidMultipleIfElseStatement.java | 17 ++++++++++ .../checks/AvoidRegexPatternNotStatic.java | 17 ++++++++++ .../java/checks/AvoidSQLRequestInLoop.java | 17 ++++++++++ .../checks/AvoidSetConstantInBatchUpdate.java | 17 ++++++++++ .../AvoidSpringRepositoryCallInLoopCheck.java | 17 ++++++++++ .../checks/AvoidStatementForDMLQueries.java | 17 ++++++++++ .../checks/AvoidUsageOfStaticCollections.java | 17 ++++++++++ .../AvoidUsingGlobalVariablesCheck.java | 17 ++++++++++ ...FreeResourcesOfAutoCloseableInterface.java | 17 ++++++++++ .../java/checks/IncrementCheck.java | 17 ++++++++++ .../InitializeBufferWithAppropriateSize.java | 17 ++++++++++ .../NoFunctionCallWhenDeclaringForLoop.java | 17 ++++++++++ .../checks/OptimizeReadFileExceptions.java | 17 ++++++++++ .../UnnecessarilyAssignValuesToVariables.java | 17 ++++++++++ .../java/checks/UseCorrectForLoop.java | 17 ++++++++++ .../checks/enums/ConstOrLiteralDeclare.java | 17 ++++++++++ .../java/utils/PrinterVisitor.java | 15 ++++----- .../java/utils/StringUtils.java | 15 ++++----- .../src/test/files/ArrayCopyCheck.java | 17 ++++++++++ .../files/AvoidConcatenateStringsInLoop.java | 17 ++++++++++ .../test/files/AvoidFullSQLRequestCheck.java | 17 ++++++++++ ...ingSizeCollectionInForEachLoopIgnored.java | 17 ++++++++++ ...voidGettingSizeCollectionInForLoopBad.java | 17 ++++++++++ ...oidGettingSizeCollectionInForLoopGood.java | 17 ++++++++++ ...GettingSizeCollectionInForLoopIgnored.java | 17 ++++++++++ ...idGettingSizeCollectionInWhileLoopBad.java | 17 ++++++++++ ...dGettingSizeCollectionInWhileLoopGood.java | 17 ++++++++++ ...ttingSizeCollectionInWhileLoopIgnored.java | 17 ++++++++++ .../files/AvoidMultipleIfElseStatement.java | 17 ++++++++++ .../AvoidMultipleIfElseStatementNoIssue.java | 17 ++++++++++ .../files/AvoidRegexPatternNotStatic.java | 17 ++++++++++ .../files/AvoidSQLRequestInLoopCheck.java | 17 ++++++++++ .../AvoidSetConstantInBatchUpdateCheck.java | 17 ++++++++++ .../AvoidSpringRepositoryCallInLoopCheck.java | 17 ++++++++++ .../files/AvoidStatementForDMLQueries.java | 17 ++++++++++ .../files/AvoidUsageOfStaticCollections.java | 17 ++++++++++ .../files/AvoidUsingGlobalVariablesCheck.java | 17 ++++++++++ ...FreeResourcesOfAutoCloseableInterface.java | 17 ++++++++++ .../files/GoodUsageOfStaticCollections.java | 17 ++++++++++ .../files/GoodWayConcatenateStringsLoop.java | 17 ++++++++++ .../src/test/files/IncrementCheck.java | 17 ++++++++++ .../InitializeBufferWithAppropriateSize.java | 17 ++++++++++ .../NoFunctionCallWhenDeclaringForLoop.java | 17 ++++++++++ .../files/OptimizeReadFileExceptionCheck.java | 17 ++++++++++ .../OptimizeReadFileExceptionCheck2.java | 17 ++++++++++ .../OptimizeReadFileExceptionCheck3.java | 17 ++++++++++ .../OptimizeReadFileExceptionCheck4.java | 17 ++++++++++ .../OptimizeReadFileExceptionCheck5.java | 17 ++++++++++ ...arilyAssignValuesToVariablesTestCheck.java | 17 ++++++++++ ...esToVariablesTestCheckWithEmptyReturn.java | 17 ++++++++++ .../test/files/UseCorrectForLoopCheck.java | 17 ++++++++++ .../src/test/files/ValidRegexPattern.java | 17 ++++++++++ .../src/test/files/ValidRegexPattern2.java | 17 ++++++++++ .../src/test/files/ValidRegexPattern3.java | 17 ++++++++++ .../java/JavaCheckRegistrarTest.java | 15 ++++----- .../java/JavaPluginTest.java | 15 ++++----- .../java/JavaRulesDefinitionTest.java | 15 ++++----- .../java/checks/ArrayCopyCheckTest.java | 17 ++++++++++ .../AvoidConcatenateStringsInLoopTest.java | 17 ++++++++++ .../checks/AvoidFullSQLRequestCheckTest.java | 17 ++++++++++ .../AvoidGettingSizeCollectionInLoopTest.java | 17 ++++++++++ .../AvoidMultipleIfElseStatementTest.java | 17 ++++++++++ .../AvoidRegexPatternNotStaticTest.java | 17 ++++++++++ .../AvoidSQLRequestInLoopCheckTest.java | 17 ++++++++++ .../AvoidSetConstantInBatchInsertTest.java | 17 ++++++++++ ...idSpringRepositoryCallInLoopCheckTest.java | 17 ++++++++++ .../AvoidStatementForDMLQueriesTest.java | 17 ++++++++++ .../AvoidUsageOfStaticCollectionsTests.java | 17 ++++++++++ ...oidUsingGlobalVariablesCheckCheckTest.java | 17 ++++++++++ ...ResourcesOfAutoCloseableInterfaceTest.java | 17 ++++++++++ .../java/checks/IncrementCheckTest.java | 17 ++++++++++ ...itializeBufferWithAppropriateSizeTest.java | 17 ++++++++++ ...oFunctionCallWhenDeclaringForLoopTest.java | 17 ++++++++++ .../OptimizeReadFileExceptionCheckTest.java | 17 ++++++++++ ...ecessarilyAssignValuesToVariablesTest.java | 17 ++++++++++ .../java/checks/UseCorrectLoopCheckTest.java | 17 ++++++++++ .../java/utils/FilesUtils.java | 15 ++++----- .../java/utils/StringUtilsTest.java | 15 ++++----- pom.xml | 31 +++++++++++++++++++ 86 files changed, 1386 insertions(+), 70 deletions(-) diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java index 5ca219399..b66e81cfa 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java @@ -1,15 +1,16 @@ /* - * Copyright (C) 2023 Green Code Initiative + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaPlugin.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaPlugin.java index 3ccc016e8..ff070c1b1 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaPlugin.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaPlugin.java @@ -1,15 +1,16 @@ /* - * Copyright (C) 2023 Green Code Initiative + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java index e8f7cccd3..958edc829 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/JavaRulesDefinition.java @@ -1,15 +1,16 @@ /* - * Copyright (C) 2023 Green Code Initiative + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java index 080fc83d1..b594af9d4 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.ArrayList; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java index 90d68b852..99b732c50 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoop.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Arrays; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java index e8dd5d28b..88ff715c4 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.List; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java index 7112bb685..c81d79534 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoop.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Arrays; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java index 4cf870ea2..383365309 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatement.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.HashMap; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java index a4e8e2f7e..2561a6c0f 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStatic.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Collections; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java index 297895e08..7c4ff5623 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoop.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Arrays; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java index 06e63179b..4fe31abda 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchUpdate.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.sql.PreparedStatement; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java index 6cf843392..e95d75e98 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Arrays; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java index f273ae707..04e7b619e 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueries.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Collections; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java index c6eba94b7..18a7fb7f9 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollections.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Collections; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java index bdc4dee1b..98bb254b4 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Arrays; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java index fb41ba0f7..47cbc2eb1 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterface.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.ArrayList; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java index 7b480b1c7..00c3094dd 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Collections; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java index bb3cc4dd6..44caa8722 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSize.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Collections; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java index 1c7c47347..d4088bd22 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoop.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.ArrayList; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java index 9766d2009..2362404be 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptions.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java index 8c6dde8f0..f5544d2e5 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariables.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.sonar.check.Rule; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java index 6da7c13c1..05e46a4ab 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/UseCorrectForLoop.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Arrays; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/enums/ConstOrLiteralDeclare.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/enums/ConstOrLiteralDeclare.java index f6ece9e7b..db01a76bc 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/enums/ConstOrLiteralDeclare.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/checks/enums/ConstOrLiteralDeclare.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks.enums; import java.math.BigDecimal; diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/PrinterVisitor.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/PrinterVisitor.java index 7e796b1a3..2b709d790 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/PrinterVisitor.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/PrinterVisitor.java @@ -1,15 +1,16 @@ /* - * Copyright (C) 2023 Green Code Initiative + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . diff --git a/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/StringUtils.java b/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/StringUtils.java index bc6ec9d89..b9b81c526 100644 --- a/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/StringUtils.java +++ b/java-plugin/src/main/java/fr/greencodeinitiative/java/utils/StringUtils.java @@ -1,15 +1,16 @@ /* - * Copyright (C) 2023 Green Code Initiative + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . diff --git a/java-plugin/src/test/files/ArrayCopyCheck.java b/java-plugin/src/test/files/ArrayCopyCheck.java index d18890515..09c780eaa 100644 --- a/java-plugin/src/test/files/ArrayCopyCheck.java +++ b/java-plugin/src/test/files/ArrayCopyCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ import java.util.Arrays; import java.util.Collection; import java.util.Collections; diff --git a/java-plugin/src/test/files/AvoidConcatenateStringsInLoop.java b/java-plugin/src/test/files/AvoidConcatenateStringsInLoop.java index b6b36b2f1..4e2a5877a 100644 --- a/java-plugin/src/test/files/AvoidConcatenateStringsInLoop.java +++ b/java-plugin/src/test/files/AvoidConcatenateStringsInLoop.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.utils; public class AvoidConcatenateStringsInLoop { diff --git a/java-plugin/src/test/files/AvoidFullSQLRequestCheck.java b/java-plugin/src/test/files/AvoidFullSQLRequestCheck.java index 4a0994727..b388252af 100644 --- a/java-plugin/src/test/files/AvoidFullSQLRequestCheck.java +++ b/java-plugin/src/test/files/AvoidFullSQLRequestCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.regex.Pattern; diff --git a/java-plugin/src/test/files/AvoidGettingSizeCollectionInForEachLoopIgnored.java b/java-plugin/src/test/files/AvoidGettingSizeCollectionInForEachLoopIgnored.java index 18d38b49b..46963cd7f 100644 --- a/java-plugin/src/test/files/AvoidGettingSizeCollectionInForEachLoopIgnored.java +++ b/java-plugin/src/test/files/AvoidGettingSizeCollectionInForEachLoopIgnored.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Collection; diff --git a/java-plugin/src/test/files/AvoidGettingSizeCollectionInForLoopBad.java b/java-plugin/src/test/files/AvoidGettingSizeCollectionInForLoopBad.java index dec9e0f8a..3c74c86dc 100644 --- a/java-plugin/src/test/files/AvoidGettingSizeCollectionInForLoopBad.java +++ b/java-plugin/src/test/files/AvoidGettingSizeCollectionInForLoopBad.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Collection; diff --git a/java-plugin/src/test/files/AvoidGettingSizeCollectionInForLoopGood.java b/java-plugin/src/test/files/AvoidGettingSizeCollectionInForLoopGood.java index 840ace8cc..5f2bcd2e7 100644 --- a/java-plugin/src/test/files/AvoidGettingSizeCollectionInForLoopGood.java +++ b/java-plugin/src/test/files/AvoidGettingSizeCollectionInForLoopGood.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Collection; diff --git a/java-plugin/src/test/files/AvoidGettingSizeCollectionInForLoopIgnored.java b/java-plugin/src/test/files/AvoidGettingSizeCollectionInForLoopIgnored.java index 719f620c2..544e08e7d 100644 --- a/java-plugin/src/test/files/AvoidGettingSizeCollectionInForLoopIgnored.java +++ b/java-plugin/src/test/files/AvoidGettingSizeCollectionInForLoopIgnored.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Collection; diff --git a/java-plugin/src/test/files/AvoidGettingSizeCollectionInWhileLoopBad.java b/java-plugin/src/test/files/AvoidGettingSizeCollectionInWhileLoopBad.java index 32c74e128..f47570c9b 100644 --- a/java-plugin/src/test/files/AvoidGettingSizeCollectionInWhileLoopBad.java +++ b/java-plugin/src/test/files/AvoidGettingSizeCollectionInWhileLoopBad.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Collection; diff --git a/java-plugin/src/test/files/AvoidGettingSizeCollectionInWhileLoopGood.java b/java-plugin/src/test/files/AvoidGettingSizeCollectionInWhileLoopGood.java index 7329fba97..57668687e 100644 --- a/java-plugin/src/test/files/AvoidGettingSizeCollectionInWhileLoopGood.java +++ b/java-plugin/src/test/files/AvoidGettingSizeCollectionInWhileLoopGood.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Collection; diff --git a/java-plugin/src/test/files/AvoidGettingSizeCollectionInWhileLoopIgnored.java b/java-plugin/src/test/files/AvoidGettingSizeCollectionInWhileLoopIgnored.java index ca913f17d..10c752f40 100644 --- a/java-plugin/src/test/files/AvoidGettingSizeCollectionInWhileLoopIgnored.java +++ b/java-plugin/src/test/files/AvoidGettingSizeCollectionInWhileLoopIgnored.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Collection; diff --git a/java-plugin/src/test/files/AvoidMultipleIfElseStatement.java b/java-plugin/src/test/files/AvoidMultipleIfElseStatement.java index 1b3b9fc96..435218fa6 100644 --- a/java-plugin/src/test/files/AvoidMultipleIfElseStatement.java +++ b/java-plugin/src/test/files/AvoidMultipleIfElseStatement.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; class AvoidMultipleIfElseStatementCheck { diff --git a/java-plugin/src/test/files/AvoidMultipleIfElseStatementNoIssue.java b/java-plugin/src/test/files/AvoidMultipleIfElseStatementNoIssue.java index d3a57b7a6..a56e9e599 100644 --- a/java-plugin/src/test/files/AvoidMultipleIfElseStatementNoIssue.java +++ b/java-plugin/src/test/files/AvoidMultipleIfElseStatementNoIssue.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; class AvoidMultipleIfElseStatementCheckNoIssue { diff --git a/java-plugin/src/test/files/AvoidRegexPatternNotStatic.java b/java-plugin/src/test/files/AvoidRegexPatternNotStatic.java index 0474e4520..b5e19c6e3 100644 --- a/java-plugin/src/test/files/AvoidRegexPatternNotStatic.java +++ b/java-plugin/src/test/files/AvoidRegexPatternNotStatic.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.regex.Pattern; diff --git a/java-plugin/src/test/files/AvoidSQLRequestInLoopCheck.java b/java-plugin/src/test/files/AvoidSQLRequestInLoopCheck.java index 4981d0b4c..753a717a6 100644 --- a/java-plugin/src/test/files/AvoidSQLRequestInLoopCheck.java +++ b/java-plugin/src/test/files/AvoidSQLRequestInLoopCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.sql.Connection; diff --git a/java-plugin/src/test/files/AvoidSetConstantInBatchUpdateCheck.java b/java-plugin/src/test/files/AvoidSetConstantInBatchUpdateCheck.java index 122a48b4d..03f5e86ab 100644 --- a/java-plugin/src/test/files/AvoidSetConstantInBatchUpdateCheck.java +++ b/java-plugin/src/test/files/AvoidSetConstantInBatchUpdateCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.math.BigDecimal; diff --git a/java-plugin/src/test/files/AvoidSpringRepositoryCallInLoopCheck.java b/java-plugin/src/test/files/AvoidSpringRepositoryCallInLoopCheck.java index c4aec153c..d2ae74e8a 100644 --- a/java-plugin/src/test/files/AvoidSpringRepositoryCallInLoopCheck.java +++ b/java-plugin/src/test/files/AvoidSpringRepositoryCallInLoopCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.springframework.beans.factory.annotation.Autowired; diff --git a/java-plugin/src/test/files/AvoidStatementForDMLQueries.java b/java-plugin/src/test/files/AvoidStatementForDMLQueries.java index 70ba4ed5e..5059b0933 100644 --- a/java-plugin/src/test/files/AvoidStatementForDMLQueries.java +++ b/java-plugin/src/test/files/AvoidStatementForDMLQueries.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.sql.Connection; diff --git a/java-plugin/src/test/files/AvoidUsageOfStaticCollections.java b/java-plugin/src/test/files/AvoidUsageOfStaticCollections.java index ac1b9f0dc..353099720 100644 --- a/java-plugin/src/test/files/AvoidUsageOfStaticCollections.java +++ b/java-plugin/src/test/files/AvoidUsageOfStaticCollections.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.*; diff --git a/java-plugin/src/test/files/AvoidUsingGlobalVariablesCheck.java b/java-plugin/src/test/files/AvoidUsingGlobalVariablesCheck.java index 362510eff..557d6fc92 100644 --- a/java-plugin/src/test/files/AvoidUsingGlobalVariablesCheck.java +++ b/java-plugin/src/test/files/AvoidUsingGlobalVariablesCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ public class Openclass { public static double price = 15.24; // Noncompliant {{Avoid using global variables}} public static long pages = 1053; // Noncompliant {{Avoid using global variables}} diff --git a/java-plugin/src/test/files/FreeResourcesOfAutoCloseableInterface.java b/java-plugin/src/test/files/FreeResourcesOfAutoCloseableInterface.java index e2ca15225..e1eaab59e 100644 --- a/java-plugin/src/test/files/FreeResourcesOfAutoCloseableInterface.java +++ b/java-plugin/src/test/files/FreeResourcesOfAutoCloseableInterface.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.io.*; diff --git a/java-plugin/src/test/files/GoodUsageOfStaticCollections.java b/java-plugin/src/test/files/GoodUsageOfStaticCollections.java index 8f8e55c71..6d2d3c202 100644 --- a/java-plugin/src/test/files/GoodUsageOfStaticCollections.java +++ b/java-plugin/src/test/files/GoodUsageOfStaticCollections.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.*; diff --git a/java-plugin/src/test/files/GoodWayConcatenateStringsLoop.java b/java-plugin/src/test/files/GoodWayConcatenateStringsLoop.java index b4218d0d7..c11c1ab6a 100644 --- a/java-plugin/src/test/files/GoodWayConcatenateStringsLoop.java +++ b/java-plugin/src/test/files/GoodWayConcatenateStringsLoop.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.utils; public class GoodWayConcatenateStringsLoop { diff --git a/java-plugin/src/test/files/IncrementCheck.java b/java-plugin/src/test/files/IncrementCheck.java index 6a6d1b536..54b20bf90 100644 --- a/java-plugin/src/test/files/IncrementCheck.java +++ b/java-plugin/src/test/files/IncrementCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ class MyClass { MyClass(MyClass mc) { } diff --git a/java-plugin/src/test/files/InitializeBufferWithAppropriateSize.java b/java-plugin/src/test/files/InitializeBufferWithAppropriateSize.java index 1b391c106..b5852a195 100644 --- a/java-plugin/src/test/files/InitializeBufferWithAppropriateSize.java +++ b/java-plugin/src/test/files/InitializeBufferWithAppropriateSize.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.sql.Connection; diff --git a/java-plugin/src/test/files/NoFunctionCallWhenDeclaringForLoop.java b/java-plugin/src/test/files/NoFunctionCallWhenDeclaringForLoop.java index 8b92a39a8..da72a3efd 100644 --- a/java-plugin/src/test/files/NoFunctionCallWhenDeclaringForLoop.java +++ b/java-plugin/src/test/files/NoFunctionCallWhenDeclaringForLoop.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ class NoFunctionCallWhenDeclaringForLoop { NoFunctionCallWhenDeclaringForLoop(NoFunctionCallWhenDeclaringForLoop mc) { } diff --git a/java-plugin/src/test/files/OptimizeReadFileExceptionCheck.java b/java-plugin/src/test/files/OptimizeReadFileExceptionCheck.java index 6e7a6e29c..e9fd260cb 100644 --- a/java-plugin/src/test/files/OptimizeReadFileExceptionCheck.java +++ b/java-plugin/src/test/files/OptimizeReadFileExceptionCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Arrays; diff --git a/java-plugin/src/test/files/OptimizeReadFileExceptionCheck2.java b/java-plugin/src/test/files/OptimizeReadFileExceptionCheck2.java index 2e1054925..689dc1878 100644 --- a/java-plugin/src/test/files/OptimizeReadFileExceptionCheck2.java +++ b/java-plugin/src/test/files/OptimizeReadFileExceptionCheck2.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Arrays; diff --git a/java-plugin/src/test/files/OptimizeReadFileExceptionCheck3.java b/java-plugin/src/test/files/OptimizeReadFileExceptionCheck3.java index e76f64a01..92dc15019 100644 --- a/java-plugin/src/test/files/OptimizeReadFileExceptionCheck3.java +++ b/java-plugin/src/test/files/OptimizeReadFileExceptionCheck3.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Arrays; diff --git a/java-plugin/src/test/files/OptimizeReadFileExceptionCheck4.java b/java-plugin/src/test/files/OptimizeReadFileExceptionCheck4.java index 89ca97340..5914e0fa5 100644 --- a/java-plugin/src/test/files/OptimizeReadFileExceptionCheck4.java +++ b/java-plugin/src/test/files/OptimizeReadFileExceptionCheck4.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Arrays; diff --git a/java-plugin/src/test/files/OptimizeReadFileExceptionCheck5.java b/java-plugin/src/test/files/OptimizeReadFileExceptionCheck5.java index b4c3388dd..6d8b553e2 100644 --- a/java-plugin/src/test/files/OptimizeReadFileExceptionCheck5.java +++ b/java-plugin/src/test/files/OptimizeReadFileExceptionCheck5.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Arrays; diff --git a/java-plugin/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheck.java b/java-plugin/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheck.java index b61a58ec7..17eb069a5 100644 --- a/java-plugin/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheck.java +++ b/java-plugin/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; class UnnecessarilyAssignValuesToVariablesTestCheck { diff --git a/java-plugin/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java b/java-plugin/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java index f732e4945..f70c4c410 100644 --- a/java-plugin/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java +++ b/java-plugin/src/test/files/UnnecessarilyAssignValuesToVariablesTestCheckWithEmptyReturn.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; class UnnecessarilyAssignValuesToVariablesTestCheck { diff --git a/java-plugin/src/test/files/UseCorrectForLoopCheck.java b/java-plugin/src/test/files/UseCorrectForLoopCheck.java index dfdde5d16..350ed6ebb 100644 --- a/java-plugin/src/test/files/UseCorrectForLoopCheck.java +++ b/java-plugin/src/test/files/UseCorrectForLoopCheck.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.Arrays; diff --git a/java-plugin/src/test/files/ValidRegexPattern.java b/java-plugin/src/test/files/ValidRegexPattern.java index 5ed3652f4..aacb701e5 100644 --- a/java-plugin/src/test/files/ValidRegexPattern.java +++ b/java-plugin/src/test/files/ValidRegexPattern.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.regex.Pattern; diff --git a/java-plugin/src/test/files/ValidRegexPattern2.java b/java-plugin/src/test/files/ValidRegexPattern2.java index d6d9efd71..a674b9bc4 100644 --- a/java-plugin/src/test/files/ValidRegexPattern2.java +++ b/java-plugin/src/test/files/ValidRegexPattern2.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.regex.Pattern; diff --git a/java-plugin/src/test/files/ValidRegexPattern3.java b/java-plugin/src/test/files/ValidRegexPattern3.java index e19073454..086769384 100644 --- a/java-plugin/src/test/files/ValidRegexPattern3.java +++ b/java-plugin/src/test/files/ValidRegexPattern3.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import java.util.regex.Pattern; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaCheckRegistrarTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaCheckRegistrarTest.java index 29cc52ae2..db1383ae5 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaCheckRegistrarTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaCheckRegistrarTest.java @@ -1,15 +1,16 @@ /* - * Copyright (C) 2023 Green Code Initiative + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java index 3d09e5b0e..0f2167d37 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaPluginTest.java @@ -1,15 +1,16 @@ /* - * Copyright (C) 2023 Green Code Initiative + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java index bb6f796d3..2c6551436 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/JavaRulesDefinitionTest.java @@ -1,15 +1,16 @@ /* - * Copyright (C) 2023 Green Code Initiative + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/ArrayCopyCheckTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/ArrayCopyCheckTest.java index e83a49e2f..5f0b12767 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/ArrayCopyCheckTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/ArrayCopyCheckTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoopTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoopTest.java index d5e3e6fcb..00027474c 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoopTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidConcatenateStringsInLoopTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheckTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheckTest.java index 516f31fec..25ead7c4d 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheckTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidFullSQLRequestCheckTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoopTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoopTest.java index 4a0bad7f8..8083c1db6 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoopTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidGettingSizeCollectionInLoopTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementTest.java index 84a7e5f32..568757e7c 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidMultipleIfElseStatementTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStaticTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStaticTest.java index a3c8ba912..5350cc127 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStaticTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidRegexPatternNotStaticTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheckTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheckTest.java index 54f5f4a53..5abed41fd 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheckTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidSQLRequestInLoopCheckTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchInsertTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchInsertTest.java index 73a7e58d3..8c138fde7 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchInsertTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidSetConstantInBatchInsertTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheckTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheckTest.java index ce5dfc36e..2ea1887bd 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheckTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidSpringRepositoryCallInLoopCheckTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import fr.greencodeinitiative.java.utils.FilesUtils; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueriesTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueriesTest.java index 1a8803440..40c5a51b6 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueriesTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidStatementForDMLQueriesTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollectionsTests.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollectionsTests.java index e72d271de..a9b8a2d84 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollectionsTests.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsageOfStaticCollectionsTests.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheckCheckTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheckCheckTest.java index c8dbeb26a..f9e270e6c 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheckCheckTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/AvoidUsingGlobalVariablesCheckCheckTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterfaceTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterfaceTest.java index 2736a12e3..9a9ca4929 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterfaceTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/FreeResourcesOfAutoCloseableInterfaceTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/IncrementCheckTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/IncrementCheckTest.java index 4044341cd..e9d5b98ef 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/IncrementCheckTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/IncrementCheckTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSizeTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSizeTest.java index 5096eee2f..deef83e80 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSizeTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/InitializeBufferWithAppropriateSizeTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoopTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoopTest.java index f2876bb1d..ef3c983fe 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoopTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/NoFunctionCallWhenDeclaringForLoopTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheckTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheckTest.java index 5dffac408..b3ef8c89e 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheckTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/OptimizeReadFileExceptionCheckTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTest.java index efcb2aa1b..09336e24a 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/UnnecessarilyAssignValuesToVariablesTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/UseCorrectLoopCheckTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/UseCorrectLoopCheckTest.java index f6add5776..815d097a1 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/UseCorrectLoopCheckTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/checks/UseCorrectLoopCheckTest.java @@ -1,3 +1,20 @@ +/* + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ package fr.greencodeinitiative.java.checks; import org.junit.jupiter.api.Test; diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/FilesUtils.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/FilesUtils.java index 121607764..ed06d4cef 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/FilesUtils.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/FilesUtils.java @@ -1,15 +1,16 @@ /* - * Copyright (C) 2023 Green Code Initiative + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . diff --git a/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/StringUtilsTest.java b/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/StringUtilsTest.java index 25b5b6791..9e6d9328a 100644 --- a/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/StringUtilsTest.java +++ b/java-plugin/src/test/java/fr/greencodeinitiative/java/utils/StringUtilsTest.java @@ -1,15 +1,16 @@ /* - * Copyright (C) 2023 Green Code Initiative + * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs + * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . diff --git a/pom.xml b/pom.xml index 45989d064..f30d9ec81 100644 --- a/pom.xml +++ b/pom.xml @@ -9,6 +9,7 @@ ecoCode Sonar Plugins Project Provides rules to reduce the environmental footprint of your programs + 2023 https://github.com/green-code-initiative/ecocode green-code-initiative @@ -261,6 +262,36 @@ + + + com.mycila + license-maven-plugin + 4.1 + + + Green Code Initiative + https://www.ecocode.io + + + +
      com/mycila/maven/plugin/license/templates/GPL-3.txt
      + + **/*.java + +
      +
      +
      + + + validate + + check + + validate + + +
      +
      From a12180a0c8a991dd4e61da2a5262260ed7291f37 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 15 Sep 2023 11:40:39 +0200 Subject: [PATCH 167/170] refacto - upgrade licences : update CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5417e622f..e29995a9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#216](https://github.com/green-code-initiative/ecoCode/issues/216) Upgrade rule EC2 for Java : Multiple if-else statement improvment - [#106](https://github.com/green-code-initiative/ecoCode/issues/106) Upgrade RULES.md : rule EC67 not relevant neither for Python nor Rust +- [#225](https://github.com/green-code-initiative/ecoCode/pull/225) Upgrade licence system and licence headers of Java files ### Deleted From 1bd5870b5fe3911261650982c5315ec305377b11 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 22 Sep 2023 12:40:21 +0200 Subject: [PATCH 168/170] [ISSUE 140] rule EC3 : no implementation for python --- RULES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RULES.md b/RULES.md index 21f34dafa..2ef1b13bc 100644 --- a/RULES.md +++ b/RULES.md @@ -36,7 +36,7 @@ Some are applicable for different technologies. | EC72 | Perform an SQL query inside a loop | Servers are optimized to process multiple selections, insertions, or changes in a single query or transaction. consume CPU cycles, RAM, and bandwidth unnecessarily. | [cnumr best practices (3rd edition) BP_072](https://github.com/cnumr/best-practices/blob/main/chapters/BP_072_fr.md) | ✅ | ✅ | 🚀 | ✅ | 🚀 | | EC74 | Write SELECT * FROM | The database server must resolve the fields based on the schema. If you are familiar with the diagram, it is strongly recommended to name the fields. | [cnumr best practices (3rd edition) BP_074 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | ✅ | 🚀 | | EC1 | Calling a Spring repository inside a loop | The use of Spring repository in a loop induces unnecessary calculations by the CPU and therefore superfluous energy consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | -| EC3 | Getting the size of the collection in the loop | When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. | | ✅ | ✅ | 🚀 | 🚀 | 🚀 | +| EC3 | Getting the size of the collection in the loop | When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. | | ✅ | ✅ | 🚀 | 🚫 | 🚀 | | EC2 | Multiple if-else statement | Using too many conditional if-else statements will impact performance since JVM will have to compare the conditions. Prefer using a switch statement instead of multiple if-else if possible, or refactor your code to reduce conditonnal statements on the same variable. Switch statement has a performance advantage over if – else. | | ✅ | ✅ | 🚀 | 🚧 | 🚀 | | EC76 | Usage of static collections | Avoid usage of static collections. If you want to use static collections make them final and create for example a singleton if needed containing the collections. The static fields are more complicated for the Garbage Collector to manage and can lead to memory leaks. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | | EC77 | Usage Pattern.compile() in a non-static context | Avoid using Pattern.compile() in a non-static context. This operation requires a non negligible amount of computational power, Using a single match saves CPU cycles and RAM consumption. | | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | From f55d00c0ee397c8c097e73e1df9190dec92d407e Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 22 Sep 2023 12:41:51 +0200 Subject: [PATCH 169/170] [ISSUE 140] rule EC3 : no implementation for python - CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e29995a9e..da4c47bd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#216](https://github.com/green-code-initiative/ecoCode/issues/216) Upgrade rule EC2 for Java : Multiple if-else statement improvment - [#106](https://github.com/green-code-initiative/ecoCode/issues/106) Upgrade RULES.md : rule EC67 not relevant neither for Python nor Rust - [#225](https://github.com/green-code-initiative/ecoCode/pull/225) Upgrade licence system and licence headers of Java files +- [#140](https://github.com/green-code-initiative/ecoCode/issues/140) Upgrade rule EC3 for Python : no implementation possible for python ### Deleted From 67e93e7b2f817d687b0011666caac4f70904fb85 Mon Sep 17 00:00:00 2001 From: David DE CARVALHO Date: Fri, 22 Sep 2023 12:47:52 +0200 Subject: [PATCH 170/170] [ISSUE 136] rule EC53 : no implementation for python --- CHANGELOG.md | 1 + RULES.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da4c47bd5..96d824280 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#106](https://github.com/green-code-initiative/ecoCode/issues/106) Upgrade RULES.md : rule EC67 not relevant neither for Python nor Rust - [#225](https://github.com/green-code-initiative/ecoCode/pull/225) Upgrade licence system and licence headers of Java files - [#140](https://github.com/green-code-initiative/ecoCode/issues/140) Upgrade rule EC3 for Python : no implementation possible for python +- [#136](https://github.com/green-code-initiative/ecoCode/issues/136) Upgrade rule EC53 for Python : no implementation possible for python ### Deleted diff --git a/RULES.md b/RULES.md index 2ef1b13bc..dd5832c84 100644 --- a/RULES.md +++ b/RULES.md @@ -27,7 +27,7 @@ Some are applicable for different technologies. | EC22 | The use of methods for basic operations | Using methods for basic operations consumes additional system resources. The interpreter must in effect and solve the objects and then the methods, just to carry out these simple operations of the language. | [cnumr best practices (3rd edition) BP_048 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | ✅ | 🚀 | 🚀 | 🚀 | | ??? | Call a DOM element multiple times without caching (linter key : `@ecocode/no-multiple-access-dom-element`) | Access to the Document Object Model (DOM) is costly in terms of CPU resources (CPU cycles). Also, when you use the same DOM element from JavaScript multiple times, store its reference in a variable so that you do not go through the DOM again for the same element. | [cnumr best practices (3rd edition) BP_049](https://github.com/cnumr/best-practices/blob/main/chapters/BP_049_fr.md) | 🚫 | 🚫 | ✅ | 🚫 | 🚫 | | EC4 | Use global variables | When using a global variable, the interpretation engine must check: 1) that it exists in the current scope, in the one above, etc. ; 2) the variable has a value; 3) ... To avoid all these checks, it is often possible to pass the useful variables as arguments of routines, making them local. This process saves computational time (CPU cycles). | [cnumr best practices (3rd edition) BP_050 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | ✅ | 🚀 | ✅ | 🚀 | -| EC53 | Using arrays in foreach loops | foreach deduplicates items in a list before starting the enumeration. It is therefore generally more economical to use a simple for loop when you have a good command of the collection. | [cnumr best practices (3rd edition) BP_053 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | 🚀 | 🚀 | 🚀 | 🚀 | +| EC53 | Using arrays in foreach loops | foreach deduplicates items in a list before starting the enumeration. It is therefore generally more economical to use a simple for loop when you have a good command of the collection. | [cnumr best practices (3rd edition) BP_053 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | 🚀 | 🚀 | 🚫 | 🚀 | | EC7 | Rewrite native getter/setters | Overloading them lengthens the compilation and execution times of these methods, which are usually much better optimized by the language than by the developer. | [cnumr best practices (3rd edition) BP_062 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | 🚀 | 🚀 | ✅ | 🚀 | | EC63 | Unnecessarily assigning values to variables | Avoid declaring and using variables when it is not indis-thinkable. Indeed, each allocation corresponds to the RAM occupied. | [cnumr best practices (3rd edition) BP_063 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | ✅ | 🚀 | 🚀 | 🚀 | 🚀 | | EC66 | Use single quote (') instead of quotation mark (") | The shape using the quotation marks allows the developer to insert variables that will be substituted at run time. But if the string does not have a variable, use quotes instead. Thus, language will not look for variables to subtituture, which will reduce the consumption of CPU cycles. | [cnumr best practices (3rd edition) BP_066 (no longer exists in edition 4)](https://www.greenit.fr/2019/05/07/ecoconception-web-les-115-bonnes-pratiques-3eme-edition/) | 🚀 | ✅ | 🚀 | ✅ | 🚀 |