|
21 | 21 |
|
22 | 22 | import java.util.HashMap;
|
23 | 23 | import java.util.Map;
|
| 24 | +import java.util.Optional; |
24 | 25 | import java.util.Set;
|
25 | 26 | import org.sonar.check.Rule;
|
26 | 27 | import org.sonar.plugins.python.api.PythonVisitorCheck;
|
|
34 | 35 | import org.sonar.plugins.python.api.tree.Tree;
|
35 | 36 | import org.sonar.plugins.python.api.tree.Trivia;
|
36 | 37 |
|
37 |
| - |
38 | 38 | @Rule(key = "S1128")
|
39 | 39 | public class UnusedImportCheck extends PythonVisitorCheck {
|
40 | 40 |
|
41 | 41 | private static final String MESSAGE = "Remove this unused import.";
|
42 | 42 | private static final Set<String> ALLOWED_MODULES = Set.of("__future__", "typing", "typing_extensions");
|
| 43 | + private static final Set<String> ALLOWED_FQN_PREFIX = Set.of("sklearn.experimental."); |
43 | 44 |
|
44 | 45 | private final Map<String, Name> unusedImports = new HashMap<>();
|
45 | 46 |
|
@@ -79,11 +80,14 @@ public void visitImportFrom(ImportFrom importFrom) {
|
79 | 80 | for (AliasedName aliasedName : importFrom.importedNames()) {
|
80 | 81 | Name alias = aliasedName.alias();
|
81 | 82 | var importedName = alias != null ? alias : aliasedName.dottedName().names().get(0);
|
82 |
| - var importedSymbol = importedName.symbol(); |
83 |
| - // defensive programming: imported symbol should never be null, because it always binds a name |
84 |
| - if (importedSymbol != null && importedSymbol.usages().stream().filter(u -> !u.isBindingUsage()).findFirst().isEmpty()) { |
85 |
| - unusedImports.put(importedName.name(), importedName); |
86 |
| - } |
| 83 | + Optional.ofNullable(importedName.symbol()) |
| 84 | + .filter(symbol -> symbol.usages().stream().filter(u -> !u.isBindingUsage()).findFirst().isEmpty()) |
| 85 | + .filter(symbol -> |
| 86 | + Optional.ofNullable(symbol.fullyQualifiedName()) |
| 87 | + .map(fqn -> ALLOWED_FQN_PREFIX.stream().noneMatch(fqn::startsWith)) |
| 88 | + .orElse(true) |
| 89 | + ) |
| 90 | + .ifPresent(symbol -> unusedImports.put(importedName.name(), importedName)); |
87 | 91 | }
|
88 | 92 | super.visitImportFrom(importFrom);
|
89 | 93 | }
|
|
0 commit comments