-
Notifications
You must be signed in to change notification settings - Fork 93
/
ModuleNameCheck.java
61 lines (53 loc) · 2.05 KB
/
ModuleNameCheck.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* SonarQube Python Plugin
* Copyright (C) 2011-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.python.checks;
import java.util.regex.Pattern;
import org.sonar.check.Rule;
import org.sonar.check.RuleProperty;
import org.sonar.plugins.python.api.PythonSubscriptionCheck;
import org.sonar.plugins.python.api.SubscriptionCheck;
import org.sonar.plugins.python.api.tree.Tree;
@Rule(key = "S1578")
public class ModuleNameCheck extends PythonSubscriptionCheck {
private static final String DEFAULT = "(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$";
private static final String MESSAGE = "Rename this module to match this regular expression: \"%s\".";
@RuleProperty(
key = "format",
description = "Regular expression used to check the module names against.",
defaultValue = "" + DEFAULT)
public String format = DEFAULT;
private Pattern pattern = null;
@Override
public void initialize(SubscriptionCheck.Context context) {
context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, ctx -> {
String fileName = ctx.pythonFile().fileName();
int dotIndex = fileName.lastIndexOf('.');
if (dotIndex > 0) {
String moduleName = fileName.substring(0, dotIndex);
if (!pattern().matcher(moduleName).matches()) {
ctx.addFileIssue(String.format(MESSAGE, format));
}
}
});
}
private Pattern pattern() {
if (pattern == null) {
pattern = Pattern.compile(format);
}
return pattern;
}
}