【问题标题】:SonarQube: Ignore issues in blocks not working with regexSonarQube:忽略不使用正则表达式的块中的问题
【发布时间】:2017-03-29 06:38:17
【问题描述】:

我按照相关说明进行操作 Ignore Issues in Blocks 但由于它不起作用,我怀疑它可能与正则表达式而不是声纳配置有关。

我有一些由 EMF 生成的代码。我将代码生成模板更改为在块末尾添加 //end-generated 标记,如下所示:

/*
* @generated
*/
public class MyGeneratedClass implements Enumerator {

    /*
    * @generated
    */  
    public void myGeneratedMethod() {
        // some code that SonarQube doesn't like

    } //end-generated

}

这个想法是正则表达式必须只匹配方法块。因此,START-BLOCK 必须与文本 @generated 匹配,只要它在评论终止后不跟 'class'、'enum' 或 'interface' 字样。

我创建了这个正则表达式:

对于起始块:

@generated\h*\s[\s\*]*\/(?!\s*[^\s]*\s*(class|enum|interface)\s)

对于结束块:

\/\/end-generated

这在我的测试中使用了带有 Java Pattern 类的简单代码,对于上面的类示例返回 true:

public static void main(String[] args) throws IOException {
    String regex = "@generated\\h*\\s[\\s\\*]*\\/(?!\\s*[^\\s]*\\s*(class|enum|interface)\\s)";
    String text = new String(Files.readAllBytes(Paths.get("test.txt")));
    Matcher matcher = Pattern.compile(regex).matcher(text);
    System.out.println(matcher.find());
}

但是,当我将它添加到 SonarQube 配置时,它不起作用,SonarQube 仍然报告在生成的方法中发现的问题。
我在以下位置添加了正则表达式:
SonarQube » 设置 » 排除 » 问题 » 忽略块中的问题

我也尝试过转义版本的正则表达式,结果是一样的:

@generated\\h*\\s[\\s\\*]*\\/(?!\\s*[^\\s]*\\s*(class|enum|interface)\\s)

同样将这些设置直接添加到 Sonar 属性中也不起作用,正如我在上面提到的问题中已经报告的那样:

sonar.issue.ignore.block=rule1
sonar.issue.ignore.block.rule1.beginBlockRegexp=@generated\\h*\\s[\\s\\*]*\\/(?!\\s*[^\\s]*\\s*(class|enum|interface)\\s)
sonar.issue.ignore.block.rule1.endBlockRegexp=\\/\\/end-generated

我正在使用 SonarQube 服务器 5.1.2 并从 Sonar-ant-task 2.3 运行分析。

我想知道是不是正则表达式有问题导致 SonarQube 无法匹配它,或者可能是 SonarQube 正则表达式处理中的一些限制?

编辑:我将正则表达式更改为更简单的内容以匹配“@generated”单词,并且它起作用了。但是,如果我将 '@generated[\n\r]' 强制仅在@generated 之后有新行时才匹配,那么它就不再起作用了。
SonarQube 似乎不支持换行符等基本内容。有人可以确认吗?

【问题讨论】:

    标签: regex sonarqube sonarqube-scan sonarqube5.1


    【解决方案1】:

    我确认所有用于排除问题的模式都是逐行应用的。最后,它总是被翻译为“排除从 X 行到 Y 行的问题”。我同意这并不完美(尤其是现在我们有了精确的问题位置),但这是一个“历史”功能。我们可能不会在上面投入时间,因为我们的心情是避免复杂的配置。您的用例的理想解决方案是实现https://jira.sonarsource.com/browse/SONARJAVA-71

    【讨论】:

    【解决方案2】:

    由于 SonarQube 对每行应用正则表达式,我为此用例提出了不同的解决方案:

    我每行使用起始块正则表达式:(?m)@generated$,然后通过将此模式添加到结束块正则表达式以及 end-generated 来排除 class|enum|interface。

    最终配置如下:

    sonar.issue.ignore.block=rule1
    sonar.issue.ignore.block.rule1.beginBlockRegexp=(?m)@generated$
    sonar.issue.ignore.block.rule1.endBlockRegexp=\/\/\h*end-generated|\sclass\s|\senum\s|\sinterface\s
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      相关资源
      最近更新 更多