eclipse 如何使用PMD忽略短变量规则中的“id”

oo7oh9g9  于 2022-11-04  发布在  Eclipse
关注(0)|答案(3)|浏览(176)

我正在为Eclipse(Eclipse Kepler Java EE)使用PMD插件(版本4.0.2)。我已经配置了一个命名规则:短变量。
除了像"id""e"这样的参数之外,它工作得很好。我希望PMD忽略这些参数。所以我寻找了一种方法来忽略某些参数。我找到了this link(尽管它是用于phpmd的)并尝试了一下,但我似乎不能让它工作。我的配置文件看起来像这样(XML):

<?xml version="1.0"?>
<ruleset name="My PMD ruleset"
 xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
    <description>
        My PMD
    </description>
    <rule ref="rulesets/java/naming.xml/ShortVariable">
        <property name="exceptions" value="id" />
    </rule>
</ruleset>

当我尝试使用eclipse插件导入这个规则集时,它显示没有可能的规则可以导入。有什么想法吗?

wgeznvg7

wgeznvg71#

我找到了一个解决我的问题here的方法。
产生的xml如下所示:

<?xml version="1.0"?>
<ruleset name="My PMD ruleset"
 xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
    <description>
        My PMD
    </description>
    <rule ref="rulesets/java/naming.xml/ShortVariable">
        <properties>
            <property name="xpath">
                <value>
                    //VariableDeclaratorId[(string-length(@Image) &lt; 3) and (not (@Image='id'))]
                    [not(ancestor::ForInit)]
                    [not((ancestor::FormalParameter) and (ancestor::TryStatement))]
                </value>
            </property>
        </properties>
    </rule>
</ruleset>

若要忽略更多变量名,请重复以下部分:

and (not (@Image='myVariableToIgnore'))
yks3o0rb

yks3o0rb2#

以下XML对PHP工具PHPMD 2.2.3有效

<?xml version="1.0"?>
<!DOCTYPE ruleset>
<ruleset
    name="My PMD ruleset for symfony 2.5"
    xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd"
>

    <rule ref="rulesets/unusedcode.xml" />
    <rule ref="rulesets/codesize.xml" />
    <rule ref="rulesets/cleancode.xml" />
    <rule ref="rulesets/controversial.xml" />
    <rule ref="rulesets/design.xml" />
    <rule ref="rulesets/naming.xml">
       <exclude name="ShortVariable" />
    </rule>
    <rule ref="rulesets/naming.xml/ShortVariable">
        <properties>
            <property name="exceptions" value="id,em" />
        </properties>
    </rule>
</ruleset>
eqfvzcg8

eqfvzcg83#

更新xml

<rule ref="category/java/codestyle.xml/ShortVariable">
    <properties>
        <property name="xpath">
            <value>
                //VariableDeclaratorId[(string-length(@Image) &lt; 3) and (not (@Name='id'))]
                [not(ancestor::ForInit)]
                [not((ancestor::FormalParameter) and (ancestor::TryStatement))]
            </value>
        </property>
    </properties>
</rule>

相关问题