Невозможно импортировать PMD Ruleset в Eclipse
Я хотел бы использовать тот же самый набор правил в моей среде IDE (Eclipse), что мой профиль сонара.
Я получил набор правил PMD XML из Sonar Permalinks и хотел бы импортировать его в свой PMD Eclipse Plugin, но когда я попытаюсь это сделать, кнопка "ОК" деактивируется...
![Can't import a PMD Ruleset in PMD Eclipse Plugin]()
Может кто-нибудь мне помочь?
Ответы
Ответ 1
Проблема может заключаться в том, что Sonar экспортирует ваш набор правил для формата v4.x, и ваш плагин Eclipse ожидает их в формате v5.x.
Попробуйте изменить свои правила:
<rule ref="rulesets/basic.xml/UnusedNullCheckInEquals">
<priority>3</priority>
</rule>
к
<rule ref="rulesets/java/basic.xml/UnusedNullCheckInEquals">
<priority>3</priority>
</rule>
Обратите внимание на атрибут ref. Простая находка и замена все будет хорошо для вас.
Ответ 2
Мне помог совет от Ивана Николова, но мне также пришлось изменить одно правило:
<rule ref="rulesets/java/controversial.xml/UnusedModifier">
<priority>5</priority>
</rule>
к
<rule ref="rulesets/java/unusedcode.xml/UnusedModifier">
<priority>5</priority>
</rule>
Вот мой конфигурационный файл PMD из сонара, который работает для меня с PMD-плагином 4.0.2.:
<?xml version="1.0" encoding="UTF-8"?>
<ruleset xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
name="pmd-eclipse"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
<rule ref="rulesets/java/basic.xml/UnusedNullCheckInEquals">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strings.xml/StringInstantiation">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/design.xml/ConstructorCallsOverridableMethod">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strictexception.xml/AvoidCatchingNPE">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strictexception.xml/AvoidRethrowingException">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/migrating.xml/ReplaceEnumerationWithIterator">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/optimizations.xml/AvoidArrayLoops">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/unusedcode.xml/UnusedFormalParameter">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/basic.xml/ClassCastExceptionWithToArray">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strictexception.xml/AvoidThrowingNullPointerException">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/unusedcode.xml/UnusedPrivateField">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/design.xml/CompareObjectsWithEquals">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strings.xml/UseIndexOfChar">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/basic.xml/BigIntegerInstantiation">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/design.xml/FinalFieldCouldBeStatic">
<priority>4</priority>
</rule>
<rule ref="rulesets/java/naming.xml/SuspiciousEqualsMethodName">
<priority>2</priority>
</rule>
<rule ref="rulesets/java/design.xml/InstantiationToGetClass">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/naming.xml/SuspiciousHashcodeMethodName">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/coupling.xml/LooseCoupling">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/unusedcode.xml/UnusedLocalVariable">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strings.xml/UnnecessaryCaseChange">
<priority>4</priority>
</rule>
<rule ref="rulesets/java/design.xml/SingularField">
<priority>4</priority>
</rule>
<rule ref="rulesets/java/design.xml/CloseResource">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strictexception.xml/AvoidCatchingThrowable">
<priority>2</priority>
</rule>
<rule ref="rulesets/java/basic.xml/CollapsibleIfStatements">
<priority>4</priority>
</rule>
<rule ref="rulesets/java/basic.xml/UselessOperationOnImmutable">
<priority>2</priority>
</rule>
<rule ref="rulesets/java/clone.xml/CloneMethodMustImplementCloneable">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/basic.xml/UselessOverridingMethod">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/unusedcode.xml/UnusedModifier">
<priority>5</priority>
</rule>
<rule ref="rulesets/java/design.xml/PreserveStackTrace">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/optimizations.xml/UseArraysAsList">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/design.xml/EqualsNull">
<priority>2</priority>
</rule>
<rule ref="rulesets/java/basic.xml/BrokenNullCheck">
<priority>2</priority>
</rule>
<rule ref="rulesets/java/logging-jakarta-commons.xml/UseCorrectExceptionLogging">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strings.xml/InefficientStringBuffering">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/sunsecure.xml/ArrayIsStoredDirectly">
<priority>2</priority>
</rule>
<rule ref="rulesets/java/finalizers.xml/FinalizeOverloaded">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/controversial.xml/DontImportSun">
<priority>4</priority>
</rule>
<rule ref="rulesets/java/imports.xml/DontImportJavaLang">
<priority>4</priority>
</rule>
<rule ref="rulesets/java/design.xml/MissingStaticMethodInNonInstantiatableClass">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strings.xml/StringBufferInstantiationWithChar">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/optimizations.xml/UseArrayListInsteadOfVector">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strings.xml/StringToString">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/design.xml/SimplifyConditional">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/migrating.xml/ReplaceVectorWithList">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/codesize.xml/NcssMethodCount">
<priority>3</priority>
<properties>
<property name="minimum" value="50" />
</properties>
</rule>
<rule ref="rulesets/java/logging-java.xml/AvoidPrintStackTrace">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/naming.xml/MethodWithSameNameAsEnclosingClass">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/naming.xml/SuspiciousConstantFieldName">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/codesize.xml/NcssTypeCount">
<priority>3</priority>
<properties>
<property name="minimum" value="800" />
</properties>
</rule>
<rule ref="rulesets/java/design.xml/AvoidInstanceofChecksInCatchClause">
<priority>4</priority>
</rule>
<rule ref="rulesets/java/migrating.xml/IntegerInstantiation">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/migrating.xml/AvoidAssertAsIdentifier">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/design.xml/UnnecessaryLocalBeforeReturn">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/finalizers.xml/AvoidCallingFinalize">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/basic.xml/BooleanInstantiation">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/basic.xml/UnconditionalIfStatement">
<priority>2</priority>
</rule>
<rule ref="rulesets/java/clone.xml/CloneThrowsCloneNotSupportedException">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/migrating.xml/ReplaceHashtableWithMap">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/basic.xml/AvoidDecimalLiteralsInBigDecimalConstructor">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strictexception.xml/SignatureDeclareThrowsException">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/finalizers.xml/EmptyFinalizer">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/design.xml/IdempotentOperations">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strictexception.xml/ExceptionAsFlowControl">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/finalizers.xml/FinalizeDoesNotCallSuperFinalize">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strings.xml/UseStringBufferLength">
<priority>4</priority>
</rule>
<rule ref="rulesets/java/migrating.xml/AvoidEnumAsIdentifier">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/logging-java.xml/SystemPrintln">
<priority>3</priority>
</rule>
<rule ref="rulesets/java/strings.xml/UselessStringValueOf">
<priority>4</priority>
</rule>
<rule ref="rulesets/java/strings.xml/AvoidDuplicateLiterals">
<priority>3</priority>
</rule>
</ruleset>
Ответ 3
Мне пришлось добавить язык к моему правилу (правилам) XPath, например:
<rule name="DontUseDate" language="java" class="net.sourceforge.pmd.lang.rule.XPathRule" ...></rule>
Ответ 4
Ответ Иван Николов правильный. Ваша проблема - разные версии формата набора правил. В моем случае я пытался импортировать набор правил, экспортированный из версии 3.2.6 плагина PMD, в плагин версии 4.0.0. Вот мои выводы:
- Изменение пути, которое упомянул Иван Николов, необходим для всех правил. Будьте осторожны, потому что не все правила принадлежат java (я видел также правила для XML,...). Я не настолько глубоко в PMD, поэтому я не знаю, в какой версии были правила для других внедренных технологий.
- Полезно экспортировать набор правил по умолчанию для модуля PMD 4.0.0 для сравнения со старым настраиваемым файлом набора правил. Таким образом, вы можете исправить проблемы, которые могут быть обнаружены в следующей точке.
- Во время вашего поведения было исключено исключение, которое не было визуализировано. Это исключение можно увидеть в файле журнала рабочей области (/.metadata/.log) в конце. Это может дать вам понять, что еще нужно изменить. Используйте предыдущую точку, чтобы узнать, как исправить проблемы. В моем случае был изменен путь одного правила из
в
После этих изменений мне удалось импортировать вручную перенесенный файл настраиваемых наборов правил в плагин PMD 4.0.0.
Надеюсь, что это поможет.
BTW: я нахожу 4.0.0 версию плагина PMD очень плохой, поэтому я понизил до 3.2.6
Ответ 5
В дополнение к тому, что говорили другие, вы также можете найти это:
net.sourceforge.pmd.rules.XPathRule
и замените его следующим образом:
net.sourceforge.pmd.lang.rule.XPathRule
Ответ 6
Почему бы вам не использовать Sonar Eclipse? Вам не нужно беспокоиться о синхронизации наборов правил.