This commit is contained in:
yangguanbao
2017-10-25 10:41:50 +08:00
15 changed files with 286 additions and 264 deletions

View File

@@ -11,7 +11,7 @@ Help -> Install New Software...
![](https://gw.alicdn.com/tfscom/TB1Ud5kifBNTKJjSszcXXbO2VXa.png) ![](https://gw.alicdn.com/tfscom/TB1Ud5kifBNTKJjSszcXXbO2VXa.png)
`注意:有同学反映插件扫描会触发JPA插件启动后台线程执行不明任务如果不需要的话卸载JPA插件即可,目前尚未发现原因` 注意:有同学反映插件扫描会触发很多 "JPA Java Change Event Handler (Waiting)" 的任务这个是Eclipse的一个[bug](https://bugs.eclipse.org/bugs/show_bug.cgi?id=387455)因为插件在扫描的时候会对文件进行标记所以触发了JPA的任务。卸载JPA插件或者尝试升级到最新版的Eclipse。附[JPA project Change Event Handler问题解决](https://my.oschina.net/cimu/blog/278724)
## 插件使用 ## 插件使用
@@ -23,7 +23,7 @@ Help -> Install New Software...
* long或者Long初始赋值时必须使用大写的L不能是小写的l * long或者Long初始赋值时必须使用大写的L不能是小写的l
* Object的equals方法容易抛空指针异常应使用常量或确定有值的对象来调用equals。 * Object的equals方法容易抛空指针异常应使用常量或确定有值的对象来调用equals。
目前不支持代码实时检测,需要手动触发,希望更多的人加入进来一起把咱们的插件做得越来越,尽量提升研发的使用体验。 目前不支持代码实时检测,需要手动触发,希望更多的人加入进来一起把咱们的插件做得越来越,尽量提升研发的使用体验。
### 代码扫描 ### 代码扫描

View File

@@ -61,7 +61,7 @@ object CodeAnalysis {
if (monitor.isCanceled) { if (monitor.isCanceled) {
return@run Status.CANCEL_STATUS return@run Status.CANCEL_STATUS
} }
if(it.isAccessible){ if (it.isAccessible) {
it.accept(fileVisitor) it.accept(fileVisitor)
} }
} }

View File

@@ -17,8 +17,10 @@ package com.alibaba.p3c.idea.inspection
import com.alibaba.p3c.idea.config.P3cConfig import com.alibaba.p3c.idea.config.P3cConfig
import com.alibaba.p3c.idea.pmd.AliPmdProcessor import com.alibaba.p3c.idea.pmd.AliPmdProcessor
import com.alibaba.p3c.idea.util.DocumentUtils.calculateLineStart
import com.alibaba.p3c.idea.util.DocumentUtils.calculateRealOffset import com.alibaba.p3c.idea.util.DocumentUtils.calculateRealOffset
import com.alibaba.p3c.idea.util.ProblemsUtils import com.alibaba.p3c.idea.util.ProblemsUtils
import com.alibaba.p3c.pmd.lang.java.rule.comment.RemoveCommentedCodeRule
import com.beust.jcommander.internal.Lists import com.beust.jcommander.internal.Lists
import com.google.common.cache.Cache import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder import com.google.common.cache.CacheBuilder
@@ -39,9 +41,11 @@ import java.util.concurrent.TimeUnit
* @author caikang * @author caikang
* @date 2016/12/13 * @date 2016/12/13
*/ */
class AliPmdInspectionInvoker(private val psiFile: PsiFile, class AliPmdInspectionInvoker(
private val psiFile: PsiFile,
private val manager: InspectionManager, private val manager: InspectionManager,
private val rule: Rule) { private val rule: Rule
) {
val logger = Logger.getInstance(javaClass) val logger = Logger.getInstance(javaClass)
private var violations: List<RuleViolation> = emptyList() private var violations: List<RuleViolation> = emptyList()
@@ -64,15 +68,21 @@ class AliPmdInspectionInvoker(private val psiFile: PsiFile,
val virtualFile = LocalFileSystem.getInstance().findFileByPath(rv.filename) ?: continue val virtualFile = LocalFileSystem.getInstance().findFileByPath(rv.filename) ?: continue
val psiFile = PsiManager.getInstance(manager.project).findFile(virtualFile) ?: continue val psiFile = PsiManager.getInstance(manager.project).findFile(virtualFile) ?: continue
val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: continue val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: continue
val offset = calculateRealOffset(document, rv.beginLine, rv.beginColumn)
val endOffset = calculateRealOffset(document, rv.endLine, rv.endColumn) val offsets = if (rv.rule.name == RemoveCommentedCodeRule::class.java.simpleName) {
Offsets(calculateLineStart(document, rv.beginLine),
calculateLineStart(document, rv.endLine + 1) - 1)
} else {
Offsets(calculateRealOffset(document, rv.beginLine, rv.beginColumn),
calculateRealOffset(document, rv.endLine, rv.endColumn))
}
val errorMessage = if (isOnTheFly) { val errorMessage = if (isOnTheFly) {
rv.description rv.description
} else { } else {
"${rv.description} (line ${rv.beginLine})" "${rv.description} (line ${rv.beginLine})"
} }
val problemDescriptor = ProblemsUtils.createProblemDescriptorForPmdRule(psiFile, manager, val problemDescriptor = ProblemsUtils.createProblemDescriptorForPmdRule(psiFile, manager,
isOnTheFly, rv.rule.name, errorMessage, offset, endOffset, rv.beginLine) ?: continue isOnTheFly, rv.rule.name, errorMessage, offsets.start, offsets.end, rv.beginLine) ?: continue
problemDescriptors.add(problemDescriptor) problemDescriptors.add(problemDescriptor)
} }
return problemDescriptors.toTypedArray() return problemDescriptors.toTypedArray()
@@ -130,3 +140,4 @@ class AliPmdInspectionInvoker(private val psiFile: PsiFile,
} }
data class FileRule(val filePath: String, val ruleName: String) data class FileRule(val filePath: String, val ruleName: String)
data class Offsets(val start: Int, val end: Int)

View File

@@ -36,6 +36,14 @@ object DocumentUtils {
return lineOffset + calculateRealColumn(document, line, pmdColumn) return lineOffset + calculateRealColumn(document, line, pmdColumn)
} }
fun calculateLineStart(document: Document, line: Int): Int {
val maxLine = document.lineCount
if (maxLine < line) {
return -1
}
return document.getLineStartOffset(line - 1)
}
fun calculateRealColumn(document: Document, line: Int, pmdColumn: Int): Int { fun calculateRealColumn(document: Document, line: Int, pmdColumn: Int): Int {
var realColumn = pmdColumn - 1 var realColumn = pmdColumn - 1
val minusSize = PMD_TAB_SIZE - 1 val minusSize = PMD_TAB_SIZE - 1

View File

@@ -15,6 +15,7 @@
*/ */
package com.alibaba.p3c.idea.util package com.alibaba.p3c.idea.util
import com.alibaba.p3c.pmd.lang.java.rule.comment.AvoidCommentBehindStatementRule
import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemDescriptor
@@ -39,7 +40,8 @@ import com.intellij.psi.impl.source.tree.ElementType
6 6
*/ */
object ProblemsUtils { object ProblemsUtils {
private val highlightLineRules = setOf("AvoidCommentBehindStatement") private val highlightLineRules = setOf(AvoidCommentBehindStatementRule::class.java.simpleName)
fun createProblemDescriptorForPmdRule(psiFile: PsiFile, manager: InspectionManager, isOnTheFly: Boolean, fun createProblemDescriptorForPmdRule(psiFile: PsiFile, manager: InspectionManager, isOnTheFly: Boolean,
ruleName: String, desc: String, start: Int, end: Int, ruleName: String, desc: String, start: Int, end: Int,
checkLine: Int = 0, checkLine: Int = 0,

View File

@@ -16,7 +16,8 @@ version plugin_version
dependencies { dependencies {
compile group: 'org.freemarker', name: 'freemarker', version: '2.3.25-incubating' compile group: 'org.freemarker', name: 'freemarker', version: '2.3.25-incubating'
compile 'com.alibaba.p3c.idea:p3c-common:1.0.0' //compile 'com.alibaba.p3c.idea:p3c-common:1.0.0'
compile project(':p3c-common')
compile group: 'org.javassist', name: 'javassist', version: '3.21.0-GA' compile group: 'org.javassist', name: 'javassist', version: '3.21.0-GA'
} }

View File

@@ -95,7 +95,7 @@ Counter example:
a.add("1"); a.add("1");
a.add("2"); a.add("2");
for (String temp : a) { for (String temp : a) {
if ("1".equals(temp)){ if ("1".equals(temp)) {
a.remove(temp); a.remove(temp);
} }
} }
@@ -204,7 +204,7 @@ Positive example:
// please refer to the pseudo-code as follows // please refer to the pseudo-code as follows
boolean existed = (file.open(fileName, "w") != null) && (...) || (...); boolean existed = (file.open(fileName, "w") != null) && (...) || (...);
if (existed) { if (existed) {
... //...
} }
``` ```
@@ -212,7 +212,7 @@ Positive example:
```java ```java
if ((file.open(fileName, "w") != null) && (...) || (...)) { if ((file.open(fileName, "w") != null) && (...) || (...)) {
... // ...
} }
``` ```

View File

@@ -25,15 +25,15 @@ import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper;
* @date 2016/11/16 * @date 2016/11/16
*/ */
public class NodeUtils { public class NodeUtils {
public static boolean isParentOrSelf(Node descendant,Node ancestor){ public static boolean isParentOrSelf(Node descendant, Node ancestor) {
if(descendant == ancestor) { if (descendant == ancestor) {
return true; return true;
} }
if(descendant == null || ancestor == null){ if (descendant == null || ancestor == null) {
return false; return false;
} }
Node parent = descendant.jjtGetParent(); Node parent = descendant.jjtGetParent();
while(parent != ancestor && parent != null){ while (parent != ancestor && parent != null) {
parent = parent.jjtGetParent(); parent = parent.jjtGetParent();
} }
return parent == ancestor; return parent == ancestor;
@@ -41,6 +41,7 @@ public class NodeUtils {
/** /**
* TODO optimize * TODO optimize
*
* @param expression expression * @param expression expression
* @return true if wrapper type * @return true if wrapper type
*/ */

View File

@@ -11,14 +11,14 @@
<priority>1</priority> <priority>1</priority>
<example> <example>
<![CDATA[ <![CDATA[
Negative example: Negative example:
//It is hard to tell whether it is number 11 or Long 1. //It is hard to tell whether it is number 11 or Long 1.
Long warn = 1l; Long warn = 1l;
]]> ]]>
</example> </example>
<example> <example>
<![CDATA[ <![CDATA[
Positive example: Positive example:
Long notwarn = 1L; Long notwarn = 1L;
]]> ]]>
</example> </example>
@@ -31,18 +31,18 @@
<example> <example>
<![CDATA[ <![CDATA[
Negative example: Negative example:
//Magic values, except for predefined, are forbidden in coding. //Magic values, except for predefined, are forbidden in coding.
if(key.equals("Id#taobao_1")){ if (key.equals("Id#taobao_1")) {
//... //...
} }
]]> ]]>
</example> </example>
<example> <example>
<![CDATA[ <![CDATA[
Positive example: Positive example:
String KEY_PRE = "Id#taobao_1"; String KEY_PRE = "Id#taobao_1";
if(key.equals(KEY_PRE)){ if (KEY_PRE.equals(key)) {
//... //...
} }
]]> ]]>

View File

@@ -12,12 +12,12 @@
<example> <example>
<![CDATA[ <![CDATA[
switch( x ){ switch (x) {
case 1 : case 1:
break ; break;
case 2 : case 2:
break ; break;
default : default:
} }
]]> ]]>
</example> </example>
@@ -31,7 +31,7 @@
<example> <example>
<![CDATA[ <![CDATA[
if(flag) { if (flag) {
System.out.println("hello world"); System.out.println("hello world");
} }
]]> ]]>
@@ -49,7 +49,7 @@
<![CDATA[ <![CDATA[
Negative example: Negative example:
if ((file.open(fileName, "w") != null) && (...) || (...)) { if ((file.open(fileName, "w") != null) && (...) || (...)) {
... // ...
} }
]]> ]]>
</example> </example>
@@ -58,7 +58,7 @@ Negative example:
Positive example: Positive example:
boolean existed = (file.open(fileName, "w") != null) && (...) || (...); boolean existed = (file.open(fileName, "w") != null) && (...) || (...);
if (existed) { if (existed) {
... //...
} }
]]> ]]>
</example> </example>

View File

@@ -14,7 +14,7 @@
<![CDATA[ <![CDATA[
public void f(String str){ public void f(String str){
String inner = "hi"; String inner = "hi";
if(inner.equals(str)){ if (inner.equals(str)) {
System.out.println("hello world"); System.out.println("hello world");
} }
} }
@@ -34,7 +34,7 @@
Integer a = 235; Integer a = 235;
Integer b = 235; Integer b = 235;
if (a.equals(b)) { if (a.equals(b)) {
//相等 // code
} }
]]> ]]>
</example> </example>
@@ -112,7 +112,7 @@
<example> <example>
<![CDATA[ <![CDATA[
反例: Negative example:
String result; String result;
for (String string : tagNameList) { for (String string : tagNameList) {
result = result + string; result = result + string;
@@ -121,7 +121,7 @@
</example> </example>
<example> <example>
<![CDATA[ <![CDATA[
正例: Positive example:
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
for (String string : tagNameList) { for (String string : tagNameList) {
stringBuilder.append(string); stringBuilder.append(string);

View File

@@ -101,10 +101,9 @@ Negative example:
Iterator<Integer> it=b.iterator(); Iterator<Integer> it=b.iterator();
while(it.hasNext()){ while(it.hasNext()){
Integer temp = it.next(); Integer temp = it.next();
if(delCondition){ if (delCondition) {
it.remove(); it.remove();
} }
} }
]]> ]]>
</example> </example>

View File

@@ -11,7 +11,7 @@
<test-code> <test-code>
<description>UndefineMagicConstant.</description> <description>UndefineMagicConstant.</description>
<expected-problems>0</expected-problems> <expected-problems>0</expected-problems>
<code-ref id="constants-ok" /> <code-ref id="constants-ok"/>
</test-code> </test-code>
<code-fragment id="constants-err"><![CDATA[ <code-fragment id="constants-err"><![CDATA[
@@ -22,27 +22,27 @@
Boolean h = false; Boolean h = false;
Long m = 2L; Long m = 2L;
String n = ""; String n = "";
if(i > 2){ if (i > 2) {
} }
if(i > 1){ if (i > 1) {
} }
if(m > 1L){ if (m > 1L) {
} }
if(i != null){ if (i != null) {
} }
if(h != false){ if (h != false) {
} }
if(n.equals("")){ if (n.equals("")) {
} }
for(int j=0 ; j< 10 ; i++){ for (int j = 0; j < 10; i++) {
if(i > 2){ if (i > 2) {
} }
if(i != null){ if (i != null) {
} }
} }
while(k < 1){ while (k < 1) {
if(i > 2){ if (i > 2) {
} }
k++; k++;
} }
@@ -55,7 +55,7 @@
<description>UndefineMagicConstant.</description> <description>UndefineMagicConstant.</description>
<expected-problems>2</expected-problems> <expected-problems>2</expected-problems>
<expected-linenumbers>8,20</expected-linenumbers> <expected-linenumbers>8,20</expected-linenumbers>
<code-ref id="constants-err" /> <code-ref id="constants-err"/>
</test-code> </test-code>
<code-fragment id="constants-err-2"><![CDATA[ <code-fragment id="constants-err-2"><![CDATA[
@@ -73,7 +73,7 @@
<description>UndefineMagicConstant.</description> <description>UndefineMagicConstant.</description>
<expected-problems>1</expected-problems> <expected-problems>1</expected-problems>
<expected-linenumbers>3</expected-linenumbers> <expected-linenumbers>3</expected-linenumbers>
<code-ref id="constants-err-2" /> <code-ref id="constants-err-2"/>
</test-code> </test-code>
</test-data> </test-data>

View File

@@ -13,14 +13,14 @@
<test-code> <test-code>
<description>sets-UnsupportedExceptionWithModifyAsListRule-ok.</description> <description>sets-UnsupportedExceptionWithModifyAsListRule-ok.</description>
<expected-problems>0</expected-problems> <expected-problems>0</expected-problems>
<code-ref id="sets-UnsupportedExceptionWithModifyAsListRule-ok" /> <code-ref id="sets-UnsupportedExceptionWithModifyAsListRule-ok"/>
</test-code> </test-code>
<code-fragment id="sets-UnsupportedExceptionWithModifyAsListRule-warn"><![CDATA[ <code-fragment id="sets-UnsupportedExceptionWithModifyAsListRule-warn"><![CDATA[
public class Foo { public class Foo {
private void method1() { private void method1() {
if(true){ if (true) {
List<String> list = Arrays.asList("a","b","c"); List<String> list = Arrays.asList("a", "b", "c");
list.add("d"); list.add("d");
list.remove("22"); list.remove("22");
list.clear(); list.clear();
@@ -31,8 +31,8 @@
} }
private void method2() { private void method2() {
if(true){ if (true) {
List<String> list = Arrays.asList("a","b","c"); List<String> list = Arrays.asList("a", "b", "c");
list.add("d"); list.add("d");
} }
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<String>();
@@ -46,7 +46,7 @@
<description>sets-UnsupportedExceptionWithModifyAsListRule-warn.</description> <description>sets-UnsupportedExceptionWithModifyAsListRule-warn.</description>
<expected-problems>4</expected-problems> <expected-problems>4</expected-problems>
<expected-linenumbers>5,6,7,17</expected-linenumbers> <expected-linenumbers>5,6,7,17</expected-linenumbers>
<code-ref id="sets-UnsupportedExceptionWithModifyAsListRule-warn" /> <code-ref id="sets-UnsupportedExceptionWithModifyAsListRule-warn"/>
</test-code> </test-code>
</test-data> </test-data>