【发布时间】:2018-11-19 14:03:30
【问题描述】:
我正在使用 SonarQube 编写自定义规则来扫描属性和配置文件。 能否请您指导我如何编写此自定义代码。
【问题讨论】:
标签: properties sonarqube rules
我正在使用 SonarQube 编写自定义规则来扫描属性和配置文件。 能否请您指导我如何编写此自定义代码。
【问题讨论】:
标签: properties sonarqube rules
有一个java属性文件https://github.com/racodond/sonar-jproperties-plugin的插件。您可以分叉它并编写您的自定义规则。 这是一个示例规则,用于检查不允许的键和值组合
public class KeyValueCheck extends DoubleDispatchVisitorCheck {
private static final String SIMPLE_IS_PATTERN_TEMPLATE = "(%s)";
protected final Pattern patternKey;
protected final Pattern patternValue;
private final String VIOLATION_MESSAGE;
private final boolean matches;
boolean checkValue = false;
public KeyValueCheck(String key, String value, String message, boolean matches) {
VIOLATION_MESSAGE = message;
this.matches = matches;
this.patternKey = Pattern.compile(String.format(SIMPLE_IS_PATTERN_TEMPLATE, key), Pattern.CASE_INSENSITIVE);
this.patternValue = Pattern.compile(String.format(SIMPLE_IS_PATTERN_TEMPLATE, value), Pattern.CASE_INSENSITIVE);
}
@Override
public void visitKey(KeyTree tree) {
Matcher matcher = patternKey.matcher(tree.text());
if (matcher.matches()) {
checkValue = true;
}
super.visitKey(tree);
}
@Override
public void visitValue(ValueTree tree) {
if (checkValue) {
Matcher matcher = patternValue.matcher(tree.text());
if (matches == patternValue.matcher(tree.text()).matches()) {
addPreciseIssue(tree, VIOLATION_MESSAGE);
}
checkValue = false;
}
super.visitValue(tree);
}
}
【讨论】: