Writing Custom Rule Issue

98 views
Skip to first unread message

ana.mario...@gmail.com

unread,
May 15, 2018, 9:27:10 AM5/15/18
to SonarQube

 


Hi All,

I want to add a new JavaScript rule to show an issue when "jQuery.sap.require()" is used. I'm writing the rule using Java.

I'm using SonarJS and I'm following the same approach as in 

My test file is under  /sonar-custom-rules-examples/javascript-custom-rules/src/main/java/org/sonar/samples/javascript/checks and it has the following code:


My test class is under /sonar-custom-rules-examples/javascript-custom-rules/src/test/java/org/sonar/samples/javascript/checks/ and it contains the following code:



Then, my rule is under /sonar-custom-rules-examples/javascript-custom-rules/src/test/resources/checks/ and it contains the following code: 



 So, the issue is, when I run "mvn clean install" I got "[ERROR]   JQuerySapRequireFunctionUseCheckTest.test:34
Expected violation"
This error refers to that line:  ".next().atLine(1).withMessage("Remove the usage of jQuery.sap.require.")"

I have also tried without defining the lines of the rule, and I was able to see the rule on sonar, but then, when inspect a project, the issue was not raised (the rule was activated in the quality profile assigned to the project).

What am I doing wrong? I really appreciate your help.

Thank you,
Ana Mário



vilchi...@gmail.com

unread,
May 17, 2018, 9:53:08 AM5/17/18
to SonarQube
Hi,

Your rule implementation simply doesn't work (that's why unit test is failing).
You need to find callee "jQuery.sap.require", but it's not Identifier, it's DotMemberExpressionTree. So you should do something like this:

ExpressionTree callee = tree.callee();
if (callee.is(Kind.DOT_MEMBER_EXPRESSION)) {
DotMemberExpressionTree calleeAsMember = (DotMemberExpressionTree) callee;
if (calleeAsMember.property().name() == "require" && calleeAsMember.object().is(Kind.DOT_MEMBER_EXPRESSION)) {
DotMemberExpressionTree objectAsMember = (DotMemberExpressionTree) calleeAsMember.object();
if (objectAsMember.property().name() == "sap" && objectAsMember.object().is(Kind.IDENTIFIER_REFERENCE)) {
IdentifierTree identifierTree = (IdentifierTree) objectAsMember.object();
if (identifierTree.name() == "jQuery") {
// raise issue
}
}
}
}
Reply all
Reply to author
Forward
0 new messages