代码之家  ›  专栏  ›  技术社区  ›  stwissel

如何使用xpath检查pmd中的apex源字符串?

  •  0
  • stwissel  · 技术社区  · 7 年前

    PMD源代码分析器允许将规则编写为 XPath expressions .

    我正在清理一个apex代码库,我经常发现以下错误: !someCollection.isEmpty() && someCollection != null .

    正确的方法是先检查空值: someCollection != null && !someCollection.isEmpty() .

    用我的 trusted editor 我可以使用regex查找这些项目: && [a-zA-Z0-9]* != null . 很有魅力。现在我尝试为它创建一个自定义的PMD规则,但是我的xpath regex没有在PMD设计器中返回任何值:

    <rule message="Apex code must check != null before .isEmpty()" name="NullValueCheckBeforeEmptyCheck" class="net.sourceforge.pmd.lang.rule.XPathRule">
        <description>Apex code must check != null before .isEmpty()</description>
        <priority>1</priority>
        <properties>
          <property name="xpath">
            <value>
                <![CDATA[
                    //*[matches(@Image,'&& [a-zA-Z0-9]* != null')]
                ]]>
            </value>
          </property>
        </properties>
      </rule>
    

    我试着初步检查 //*[matches(@Image,'if')] 但即使这样也没有结果。

    我错过了什么?

    触发规则的示例顶点:

    global class caseShareBatch {
    
    
    global void execute(List&lt;Case&gt; caseShareList){
         if(!caseShareList.isEmpty() &amp;&amp; caseShareList != null) {
                insert caseShareList;
         }
    }
    
    }
    3 回复  |  直到 7 年前
        1
  •  1
  •   Michael Kay    7 年前

    您确定PMD支持xpath 2.0吗?从文档的快速浏览来看,这并不明显。经常有人谈论没有版本号的xpath,他们指的是xpath 1.0,当然没有。 matches() 功能。

        2
  •  1
  •   Acanda    7 年前

    PMD使用apex解析器将源代码转换为抽象语法树(ast)。您的xpath表达式应用于ast,而不是源代码。例如,if语句的ast如下所示:

    IfElseBlockStatement {
        IfBlockStatement {
            StandardCondition {
                BooleanExpression {
                    PrefixExpression {
                        MethodCallExpression {
                            ReferenceExpression 
                        }
                    }
                    BooleanExpression {
                        VariableExpression 
                        LiteralExpression 
                    }
                }
            }
            BlockStatement {
                DmlInsertStatement {
                    VariableExpression 
                }
            }
        }
    }
    

    PMD有一个图形 rule designer 这有助于编写xpath规则。

    PMD Rule Designer

    对于这个ast,xpath //BooleanExpression/BooleanExpression[position() > 0 and VariableExpression and LiteralExpression] 比赛 && caseShareList != null . 但它也会匹配 || i == 42 因此,您必须进一步细化查询。不幸的是,我没有看到任何能让我区分 && || 但你可能会有更好的运气。

        3
  •  0
  •   stwissel    7 年前

    事实证明,我需要做的是不可能与PMD6.10。这个 latest release 6.11.0 没有暴露 @Image 属性,但在布尔运算符中添加了足够多的新属性,以形成一个值为@michael kay的xpath表达式,而无需将regex添加到组合中:

    //BooleanExpression[@Op="&&"][
      child::*[2][
        self::BooleanExpression[@Op="!="][
          child::*[1][self::VariableExpression] and
          child::*[2][self::LiteralExpression[@LiteralType="NULL"]]
        ]
      ]
    ]
    

    牛传染性胃肠炎病毒