23
23
import java .util .stream .Collectors ;
24
24
import org .sonar .check .Rule ;
25
25
import org .sonar .plugins .python .api .PythonSubscriptionCheck ;
26
+ import org .sonar .plugins .python .api .quickfix .PythonQuickFix ;
27
+ import org .sonar .plugins .python .api .quickfix .PythonTextEdit ;
26
28
import org .sonar .plugins .python .api .tree .ExpressionStatement ;
27
29
import org .sonar .plugins .python .api .tree .Statement ;
28
30
import org .sonar .plugins .python .api .tree .StatementList ;
29
- import org .sonar .plugins .python .api .quickfix .PythonQuickFix ;
30
31
import org .sonar .python .quickfix .TextEditUtils ;
32
+ import org .sonar .python .tree .TreeUtils ;
31
33
32
34
import static org .sonar .plugins .python .api .tree .Tree .Kind .EXPRESSION_STMT ;
33
35
import static org .sonar .plugins .python .api .tree .Tree .Kind .PASS_STMT ;
@@ -49,21 +51,37 @@ public void initialize(Context context) {
49
51
if (statements .size () <= 1 ) {
50
52
return ;
51
53
}
52
-
53
54
statements .stream ()
54
55
.filter (st -> st .is (PASS_STMT ))
55
56
.findFirst ()
56
57
.ifPresent (st -> {
57
- var issue = ctx . addIssue ( st , MESSAGE );
58
+ var textEdit = createRemoveStatementTextEdit ( statements , st );
58
59
var quickFix = PythonQuickFix
59
60
.newQuickFix (QUICK_FIX_MESSAGE )
60
- .addTextEdit (TextEditUtils . removeStatement ( st ) )
61
+ .addTextEdit (textEdit )
61
62
.build ();
62
- issue .addQuickFix (quickFix );
63
+ ctx . addIssue ( st , MESSAGE ) .addQuickFix (quickFix );
63
64
});
64
65
});
65
66
}
66
67
68
+ private static PythonTextEdit createRemoveStatementTextEdit (List <Statement > statements , Statement toRemove ) {
69
+ var removeIndex = statements .indexOf (toRemove );
70
+ var last = removeIndex == statements .size () - 1 ;
71
+ if (last ) {
72
+ var previous = statements .get (removeIndex - 1 );
73
+ var removeFrom = TreeUtils .getTreeSeparatorOrLastToken (previous );
74
+ var removeTo = TreeUtils .getTreeSeparatorOrLastToken (toRemove );
75
+ return TextEditUtils .removeRange (
76
+ removeFrom .line (),
77
+ removeFrom .column (),
78
+ removeTo .line (),
79
+ removeTo .column ());
80
+ } else {
81
+ return TextEditUtils .removeUntil (toRemove , statements .get (removeIndex + 1 ));
82
+ }
83
+ }
84
+
67
85
private static boolean isNotStringLiteralExpressionStatement (Statement st ) {
68
86
return !(st .is (EXPRESSION_STMT ) && ((ExpressionStatement ) st ).expressions ().stream ().allMatch (e -> e .is (STRING_LITERAL )));
69
87
}
0 commit comments