diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 000000000..6313b56c5
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+* text=auto eol=lf
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 000000000..7c3fe4741
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,35 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+version: 2
+updates:
+ - package-ecosystem: "maven"
+ directory: "/p3c-pmd/"
+ schedule:
+ interval: "daily"
+ target-branch: "xenoamess_maintain_fork"
+ open-pull-requests-limit: 100
+ - package-ecosystem: "gradle"
+ directory: "/idea-plugin/"
+ schedule:
+ interval: "daily"
+ target-branch: "xenoamess_maintain_fork"
+ open-pull-requests-limit: 100
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "daily"
+ target-branch: "xenoamess_maintain_fork"
+ open-pull-requests-limit: 100
diff --git a/.github/workflows/auto-merge.yml b/.github/workflows/auto-merge.yml
new file mode 100644
index 000000000..f912337ef
--- /dev/null
+++ b/.github/workflows/auto-merge.yml
@@ -0,0 +1,14 @@
+name: auto-merge
+
+on:
+ pull_request:
+
+jobs:
+ auto-merge:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v5
+ - uses: ahmadnassri/action-dependabot-auto-merge@v2
+ with:
+ target: minor
+ github-token: ${{ secrets.mytoken }}
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 000000000..1488a9d30
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,63 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+name: Java CI
+
+on: [ push ]
+
+jobs:
+ build:
+ runs-on: ${{ matrix.os }}
+ continue-on-error: ${{ matrix.experimental }}
+ strategy:
+ matrix:
+ os: [ windows-latest , ubuntu-latest , macos-latest ]
+ java: [ 17 ]
+ experimental: [ false ]
+
+ steps:
+ - uses: actions/checkout@v5
+ - uses: actions/cache@v4
+ with:
+ path: ~/.m2
+ key: ${{ runner.os }}-gradle-m2-${{ hashFiles('**/build.gradle') }}
+ restore-keys: |
+ ${{ runner.os }}-gradle-
+ - uses: actions/cache@v4
+ with:
+ path: ~/.gradle/caches/
+ key: ${{ runner.os }}-gradle-caches-${{ hashFiles('**/build.gradle') }}
+ restore-keys: |
+ ${{ runner.os }}-gradle-
+ - uses: actions/cache@v4
+ with:
+ path: ~/.gradle/wrapper/
+ key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('**/build.gradle') }}
+ restore-keys: |
+ ${{ runner.os }}-gradle-
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@v5
+ with:
+ java-version: ${{ matrix.java }}
+ distribution: adopt
+ - name: Build Build Build!
+ run: |
+ cd ./p3c-pmd
+ chmod 777 ./mvnw
+ ./mvnw install -Penforce
+ cd ../
+ cd ./idea-plugin
+ chmod 777 ./gradlew
+ ./gradlew buildPlugin -s
diff --git a/.gitignore b/.gitignore
index 08a3264a6..9cc9538ea 100644
--- a/.gitignore
+++ b/.gitignore
@@ -71,7 +71,6 @@ configuration/**
# sass gitignore#
.sass-cache
-.idea
# tcc_coverage
coverage.ec
@@ -82,7 +81,6 @@ config.client.*
temp/
*.pid
-*.orig
hsf.configuration/
@@ -93,3 +91,6 @@ hsf.configuration/
*.instance
out
!/p3c-idea/src/main/kotlin/com/alibaba/smartfox/work/tools/aone/ui/AoneBranchView.kt
+
+#versions-maven-plugin
+*.versionsBackup
\ No newline at end of file
diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java
new file mode 100644
index 000000000..b901097f2
--- /dev/null
+++ b/.mvn/wrapper/MavenWrapperDownloader.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2007-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import java.net.*;
+import java.io.*;
+import java.nio.channels.*;
+import java.util.Properties;
+
+public class MavenWrapperDownloader {
+
+ private static final String WRAPPER_VERSION = "0.5.6";
+ /**
+ * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
+ */
+ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
+
+ /**
+ * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
+ * use instead of the default one.
+ */
+ private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
+ ".mvn/wrapper/maven-wrapper.properties";
+
+ /**
+ * Path where the maven-wrapper.jar will be saved to.
+ */
+ private static final String MAVEN_WRAPPER_JAR_PATH =
+ ".mvn/wrapper/maven-wrapper.jar";
+
+ /**
+ * Name of the property which should be used to override the default download url for the wrapper.
+ */
+ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
+
+ public static void main(String args[]) {
+ System.out.println("- Downloader started");
+ File baseDirectory = new File(args[0]);
+ System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
+
+ // If the maven-wrapper.properties exists, read it and check if it contains a custom
+ // wrapperUrl parameter.
+ File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
+ String url = DEFAULT_DOWNLOAD_URL;
+ if(mavenWrapperPropertyFile.exists()) {
+ FileInputStream mavenWrapperPropertyFileInputStream = null;
+ try {
+ mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
+ Properties mavenWrapperProperties = new Properties();
+ mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
+ url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
+ } catch (IOException e) {
+ System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
+ } finally {
+ try {
+ if(mavenWrapperPropertyFileInputStream != null) {
+ mavenWrapperPropertyFileInputStream.close();
+ }
+ } catch (IOException e) {
+ // Ignore ...
+ }
+ }
+ }
+ System.out.println("- Downloading from: " + url);
+
+ File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
+ if(!outputFile.getParentFile().exists()) {
+ if(!outputFile.getParentFile().mkdirs()) {
+ System.out.println(
+ "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
+ }
+ }
+ System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
+ try {
+ downloadFileFromURL(url, outputFile);
+ System.out.println("Done");
+ System.exit(0);
+ } catch (Throwable e) {
+ System.out.println("- Error downloading");
+ e.printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ private static void downloadFileFromURL(String urlString, File destination) throws Exception {
+ if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
+ String username = System.getenv("MVNW_USERNAME");
+ char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
+ Authenticator.setDefault(new Authenticator() {
+ @Override
+ protected PasswordAuthentication getPasswordAuthentication() {
+ return new PasswordAuthentication(username, password);
+ }
+ });
+ }
+ URL website = new URL(urlString);
+ ReadableByteChannel rbc;
+ rbc = Channels.newChannel(website.openStream());
+ FileOutputStream fos = new FileOutputStream(destination);
+ fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
+ fos.close();
+ rbc.close();
+ }
+
+}
diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar
new file mode 100644
index 000000000..2cc7d4a55
Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ
diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 000000000..642d572ce
--- /dev/null
+++ b/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1,2 @@
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
+wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
diff --git a/README.md b/README.md
index 40f20c5f3..ba7f77a7a 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,52 @@
# P3C
[](https://www.apache.org/licenses/LICENSE-2.0.html)
+[](https://sonarcloud.io/dashboard?id=p3c-idea)
+p3c-cmd
-## Preface
+[](https://sonarcloud.io/dashboard?id=p3c-idea)
+idea plugin(p3c-common)
+
+## Notice 声明
+This Third-party maintenance(TPM) here is forked from original [alibaba/p3c](https://github.com/alibaba/p3c)
+
+Follows Apache license described in [license](license.txt)
+
+Sources can be found https://github.com/XenoAmess/p3c
+
+Releases can be found at https://plugins.jetbrains.com/plugin/14109-alibaba-java-coding-guidelines-xenoamess-tpm-
+
+This TPM aims to help maintain alibaba/p3c, fix bugs, and add improvements, as the original developer is too busy to handle them.
+
+This TPM is NOT created, or maintained, or controlled by any alibaba employee, in other words it is a TPM, but not an official branch.
+
+TPM maintainer XenoAmess have no knowledge with eclipse plugin development.
+
+TPM maintainer XenoAmess suggest you only create pr for module idea-plugin and p3c-pmd, unless you really have a strong reason.
+
+## Features 特性
+
+1. This TPM can always run on latest Jetbrains-idea release/EAP.
+
+ 本第三方维护版会在任何 Jetbrains-idea release 或者EAP更新时保证可用。
+
+2. This TPM will always use as latest dependencies as possible.
+
+ 本第三方维护版会使用尽可能新的依赖版本。
+
+3. This TPM implements a mechanism for configuring black-list/white-list for rules/classes
+
+ 本第三方维护版实现有一套配置系统,可以对源码类/规则进行黑名单/白名单过滤。
+
+4. This TPM does NOT fully obey p3c rules.
+ Especially for the rule who disable deprecated functions.
+ Maintainer XenoAmess will make sure they are usable,
+ but have no enough time to eliminate every deprecated functions.
+
+ 本第三方维护版不完全遵循p3c,尤其是关于禁止使用deprecated函数的规则。
+ 维护者XenoAmess会保证函数可用,但是没有充裕的时间保证消灭每一个deprecated函数。
+
+## Preface 前言
> We are pleased to present Alibaba Java Coding Guidelines which consolidates the best programming practices over the years from Alibaba Group's technical teams. A vast number of Java programming teams impose demanding requirements on code quality across projects as we encourage reuse and better understanding of each other's programs. We have seen many programming problems in the past. For example, defective database table structures and index designs may cause software architecture flaws and performance risks. Another example is confusing code structures being difficult to maintain. Furthermore, vulnerable code without authentication is prone to hackers’ attacks. To address these kinds of problems, we developed this document for Java developers at Alibaba.
For more information please refer the *Alibaba Java Coding Guidelines*:
@@ -11,13 +55,13 @@ For more information please refer the *Alibaba Java Coding Guidelines*:
- 《阿里巴巴Java开发手册》书籍版天猫官方店: *[阿里巴巴Java开发手册最新版](https://detail.tmall.com/item.htm?spm=a220m.1000858.1000725.1.4577601asIhzbW&id=628337143778&areaId=330100&user_id=1932014659&cat_id=2&is_b=1&rn=11a322ef70720cdf5e894001e4b48b55)*
- 《码出高效》书籍版天猫官方店: *[码出高效:Java开发手册](https://detail.tmall.com/item.htm?spm=a230r.1.14.40.7dee7d6bwpO82U&id=575107529181&ns=1&abbucket=20)*
-## Introduction
+## Introduction 介绍
The project consists of 3 parts:
- [PMD implementations](p3c-pmd)
- [IntelliJ IDEA plugin](idea-plugin)
- [Eclipse plugin](eclipse-plugin)
-## Rules
+## Rules 规则
Forty-nine rules are realized based on PMD, please refer the P3C-PMD documentation for more detailed information. Four rules are implemented within IDE plugins (IDEA and Eclipse) as follows:
- ``[Mandatory]`` Using a deprecated class or method is prohibited.
@@ -34,3 +78,10 @@ The project consists of 3 parts:
3. These two methods must be overridden if self-defined object is used as the key of Map.
Note: String can be used as the key of Map since these two methods have been rewritten.
+## Config Mechanism 配置机制
+
+see
+
+[documents](idea-plugin/README.md)
+
+[说明](idea-plugin/README_cn.md)
diff --git a/build.cmd b/build.cmd
new file mode 100644
index 000000000..6a580c16c
--- /dev/null
+++ b/build.cmd
@@ -0,0 +1,18 @@
+set JAVA_HOME=C:\jdk-21\
+
+cd ./p3c-pmd
+call ./mvnw clean install -Dmaven.javadoc.skip=false -e -X
+cd ../
+cd ./idea-plugin
+
+set JAVA_HOME=C:\jdk-21\
+
+cd ./p3c-common
+call ../gradlew clean publishToMavenLocal
+cd ../
+
+cd ./p3c-idea
+call ../gradlew clean publishToMavenLocal buildPlugin
+cd ../
+
+cd ../
diff --git a/deploy.cmd b/deploy.cmd
new file mode 100644
index 000000000..3fa7b0652
--- /dev/null
+++ b/deploy.cmd
@@ -0,0 +1,19 @@
+set JAVA_HOME=C:\jdk-8\
+
+cd ./p3c-pmd
+call ./mvnw clean deploy -Dmaven.javadoc.skip=false -e -X -Psonatype-oss-release
+cd ../
+cd ./idea-plugin
+
+set JAVA_HOME=C:\jdk-21\
+
+cd ./p3c-common
+rem call ../gradlew clean install sign uploadArchives -DossrhUsername="%ossrhUsername%" -DossrhPassword="%ossrhPassword%"
+call ../gradlew publishToMavenLocal
+cd ../
+
+cd ./p3c-idea
+call ../gradlew clean publishToMavenLocal buildPlugin
+cd ../
+
+cd ../
diff --git a/eclipse-plugin/.gitignore b/eclipse-plugin/.gitignore
deleted file mode 100644
index 51836b5aa..000000000
--- a/eclipse-plugin/.gitignore
+++ /dev/null
@@ -1,97 +0,0 @@
-# Gradle
-build
-.gradle
-
-testdata/
-# Java gitignore #
-.class
-.log
-
-# Package Files #
-
-*.war
-*.ear
-*.gradle
-
-#hsf files
-configuration
-
-# maven gitignore#
-target/**
-
-.svn/
-
-# intelliJ.gitignore #
-.idea
-*.iml
-*.ipr
-*.iws
-*.bat
-
-# Eclipse git ignore#
-*.pydevproject
-.project
-.metadata
-bin/**
-*/bin/**
-tmp/**
-tmp/**/*
-configuration/**
-*.tmp
-*.bak
-*.orig
-*.swp
-*~.nib
-.classpath
-.settings/
-.loadpath
-.fileTable*
-.cache
-
-# External tool builders
-.externalToolBuilders/
-
-# Locally stored "Eclipse launch configurations"
-*.launch
-
-# CDT-specific
-.cproject
-
-# PDT-specific
-.buildpath
-
-#log
-*.log
-*.log.*
-
-# Windows Thumbs.db
-*.db
-
-# OSX
-.DS_Store
-
-# sass gitignore#
-.sass-cache
-.idea
-
-# tcc_coverage
-coverage.ec
-
-
-
-config.client.*
-
-temp/
-*.pid
-*.orig
-
-hsf.configuration/
-
-# code coverage report
-*.ec
-
-#hsf test
-*.instance
-**/target
-.pmd
-**/.pmd
diff --git a/eclipse-plugin/README.md b/eclipse-plugin/README.md
deleted file mode 100644
index 94b9dbcd1..000000000
--- a/eclipse-plugin/README.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# Eclipse Plugin
----
-## Prepare
-- Eclipse Juno+
-- maven3.+
-- JDK 1.7+
-
-## Build
-```
-mvn -U clean install
-```
-## [中文使用手册](README_cn.md)
-## Install
-1. Help >> Install New Software
-then enter this update site URL [https://p3c.alibaba.com/plugin/eclipse/update](https://p3c.alibaba.com/plugin/eclipse/update)
-
-
-
-2. Follow the wizard, restart Eclipse to take effect after install success.
-
-## Use
-1. Switch language
-
- 
-
-2. Code Analyze
-
- 
-
- 
-
diff --git a/eclipse-plugin/README_cn.md b/eclipse-plugin/README_cn.md
deleted file mode 100644
index c133a3ee4..000000000
--- a/eclipse-plugin/README_cn.md
+++ /dev/null
@@ -1,63 +0,0 @@
-> 首先非常感谢大家对插件的支持与意见,Eclipse的功能相对来说比较简单,希望有更多的同学加入进来一起完善。
-
-## 插件安装
-环境:JDK1.8,Eclipse4+。有同学遇到过这样的情况,安装插件重启后,发现没有对应的菜单项,从日志上也看不到相关的异常信息,最后把JDK从1.6升级到1.8解决问题。
-
-Help -> Install New Software...
-
-
-
-输入Update Site地址:https://p3c.alibaba.com/plugin/eclipse/update 回车,然后勾选Ali-CodeAnalysis,再一直点Next Next...按提示走下去就好。 然后就是提示重启了,安装完毕。
-
-
-
-注意:有同学反映插件扫描会触发很多 "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)
-
-
-## 插件使用
-
-目前插件实现了开发手册中的53条规则,大部分基于PMD实现,其中有4条规则基于Eclipse实现,支持4条规则的QuickFix功能。
-
- * 所有的覆写方法,必须加@Override注解,
- * if/for/while/switch/do等保留字与左右括号之间都必须加空格,
- * long或者Long初始赋值时,必须使用大写的L,不能是小写的l)
- * Object的equals方法容易抛空指针异常,应使用常量或确定有值的对象来调用equals。
-
-目前不支持代码实时检测,需要手动触发,希望更多的人加入进来一起把咱们的插件做得越来越好,尽量提升研发的使用体验。
-
-
-### 代码扫描
-可以通过右键菜单、Toolbar按钮两种方式手动触发代码检测。同时结果面板中可以对部分实现了QuickFix功能的规则进行快速修复。
-
-#### 触发扫描
-在当前编辑的文件中点击右键,可以在弹出的菜单中触发对该文件的检测。
-
-
-
-
-在左侧的Project目录树种点击右键,可以触发对整个工程或者选择的某个目录、文件进行检测。
-
-
-
-
-也可以通过Toolbar中的按钮来触发检测,目前Toolbar的按钮触发的检测范围与您IDE当时的焦点有关,如当前编辑的文件或者是Project目录树选中的项,是不是感觉与右键菜单的检测范围类似呢。
-
- 
-
-
-#### 扫描结果
-简洁的结果面板,按规则等级分类,等级->规则->文件->违规项。同时还提供一个查看规则详情的界面。
-
-清除结果标记更方便,支持上面提到的4条规则QuickFix。
-
-
-
-#### 查看所有规则
-
-
-
-#### 国际化
-
-
-
-
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/build.properties b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/build.properties
deleted file mode 100644
index 1dceaa621..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/build.properties
+++ /dev/null
@@ -1,7 +0,0 @@
-bin.includes = feature.xml,\
- feature.properties,\
- smartfox.png
-src.includes = build.properties,\
- feature.properties,\
- feature.xml,\
- smartfox.png
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.properties b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.properties
deleted file mode 100644
index 5bd3a3136..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.properties
+++ /dev/null
@@ -1,26 +0,0 @@
-feature.label = Ali-CodeAnalysis
-feature.provider_name = Alibaba
-feature.update_site_name = Alibaba IDE Portal
-
-description.text = Alibaba Java Coding Guidelines
-description.url = https://github.com/alibaba/p3c
-
-copyright.text =\
-Copyright 2017 Alibaba Java Coding Guidelines
-
-license.url = https://github.com/alibaba/p3c
-license.text =\
- Copyright 1999-2017 Alibaba Group. \n\
- \n\
- Licensed under the Apache License, Version 2.0 (the "License"); \n\
- you may not use this file except in compliance with the License. \n\
- You may obtain a copy of the License at \n\
- \n\
- http://www.apache.org/licenses/LICENSE-2.0 \n\
- \n\
- Unless required by applicable law or agreed to in writing, software \n\
- distributed under the License is distributed on an "AS IS" BASIS, \n\
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n\
- See the License for the specific language governing permissions and \n\
- limitations under the License. \n\
-
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.xml
deleted file mode 100644
index ba5102e3e..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.xml
+++ /dev/null
@@ -1,46 +0,0 @@
-
-
-
-
- Alibaba Java Coding Guidelines
-
-
-
- %copyright.text
-
-
-
- %license.text
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/pom.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/pom.xml
deleted file mode 100644
index 4fcddb1b1..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/pom.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
- 4.0.0
-
- com.alibaba.smartfox.eclipse
- smartfox-eclipse
- 2.0.1-SNAPSHOT
-
- com.alibaba.smartfox.eclipse.feature
- eclipse-feature
- 2017
-
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/smartfox.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/smartfox.png
deleted file mode 100644
index 75a2c1bb3..000000000
Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/smartfox.png and /dev/null differ
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/META-INF/MANIFEST.MF b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/META-INF/MANIFEST.MF
deleted file mode 100644
index 0732ec54b..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,59 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: com.alibaba.smartfox.eclipse.plugin
-Bundle-SymbolicName: com.alibaba.smartfox.eclipse.plugin;singleton:=true
-Bundle-Version: 2.0.1.qualifier
-Bundle-Activator: com.alibaba.smartfox.eclipse.SmartfoxActivator
-Bundle-Vendor: Alibaba
-Require-Bundle: org.eclipse.ui,
- org.eclipse.core.runtime,
- org.eclipse.jdt.core,
- org.eclipse.ui.ide,
- org.eclipse.ui.views,
- org.eclipse.core.resources,
- org.eclipse.jface.text,
- org.eclipse.ui.workbench.texteditor,
- org.eclipse.ltk.core.refactoring,
- org.eclipse.jdt.ui,
- org.eclipse.core.filebuffers,
- org.eclipse.equinox.p2.core,
- org.eclipse.equinox.p2.engine,
- org.eclipse.equinox.p2.operations,
- org.eclipse.equinox.p2.metadata.repository,
- org.eclipse.equinox.p2.ui,
- org.eclipse.equinox.p2.metadata
-Bundle-RequiredExecutionEnvironment: JavaSE-1.8
-Bundle-ActivationPolicy: lazy
-Bundle-ClassPath: target/lib/antlr-runtime.jar,
- target/lib/antlr4-runtime.jar,
- target/lib/asm.jar,
- target/lib/commons-io.jar,
- target/lib/commons-lang3.jar,
- target/lib/gson.jar,
- target/lib/javacc.jar,
- target/lib/jaxen.jar,
- target/lib/jcommander.jar,
- target/lib/log4j.jar,
- target/lib/pmd-core.jar,
- target/lib/pmd-java.jar,
- target/lib/pmd-javascript.jar,
- target/lib/pmd-vm.jar,
- target/lib/rhino.jar,
- target/lib/saxon-dom.jar,
- target/lib/saxon.jar,
- target/lib/p3c-pmd.jar,
- target/lib/kotlin-stdlib.jar,
- target/lib/statistics-client.jar,
- target/lib/guava.jar,
- target/classes/,
- .
-Bundle-Localization: plugin
-Export-Package: com.alibaba.smartfox.eclipse,
- com.alibaba.smartfox.eclipse.handler,
- com.alibaba.smartfox.eclipse.job,
- com.alibaba.smartfox.eclipse.marker,
- com.alibaba.smartfox.eclipse.pmd,
- com.alibaba.smartfox.eclipse.pmd.rule,
- com.alibaba.smartfox.eclipse.ui,
- com.alibaba.smartfox.eclipse.ui.pmd,
- com.alibaba.smartfox.eclipse.util
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/build.properties b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/build.properties
deleted file mode 100644
index b305b3680..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/build.properties
+++ /dev/null
@@ -1,14 +0,0 @@
-bin.includes = .,\
- META-INF/,\
- plugin.xml,\
- icons/,\
- target/lib/
-src.includes = icons/,\
- META-INF/,\
- plugin.xml,\
- messages.properties,\
- target/lib/,\
- src/main/kotlin,\
- pom.xml
-source.. = src/main/java/,src/main/resources
-output.. = target/classes/
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/clear.gif b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/clear.gif
deleted file mode 100644
index 2cd9c5444..000000000
Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/clear.gif and /dev/null differ
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/clear.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/clear.png
deleted file mode 100644
index 8c5c1a001..000000000
Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/clear.png and /dev/null differ
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/quickfixBulb.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/quickfixBulb.png
deleted file mode 100644
index ecc6c160a..000000000
Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/quickfixBulb.png and /dev/null differ
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/rules.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/rules.png
deleted file mode 100644
index 9990f5f1a..000000000
Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/actions/rules.png and /dev/null differ
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/ali-ide-run.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/ali-ide-run.png
deleted file mode 100644
index 754649e9c..000000000
Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/ali-ide-run.png and /dev/null differ
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/language.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/language.png
deleted file mode 100644
index b26745460..000000000
Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/language.png and /dev/null differ
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/blocker.gif b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/blocker.gif
deleted file mode 100644
index 2ff667899..000000000
Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/blocker.gif and /dev/null differ
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/class_obj.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/class_obj.png
deleted file mode 100644
index bc915da44..000000000
Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/class_obj.png and /dev/null differ
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/critical.gif b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/critical.gif
deleted file mode 100644
index a01bb24b7..000000000
Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/critical.gif and /dev/null differ
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/major.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/major.png
deleted file mode 100644
index 87adef9f9..000000000
Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/major.png and /dev/null differ
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/smartfox_logo.png b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/smartfox_logo.png
deleted file mode 100644
index 4a56fac4a..000000000
Binary files a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/icons/view/smartfox_logo.png and /dev/null differ
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/plugin.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/plugin.xml
deleted file mode 100644
index 358581b33..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/plugin.xml
+++ /dev/null
@@ -1,153 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/pom.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/pom.xml
deleted file mode 100644
index 2843498f3..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/pom.xml
+++ /dev/null
@@ -1,124 +0,0 @@
-
-
- 4.0.0
-
- com.alibaba.smartfox.eclipse
- smartfox-eclipse
- 2.0.1-SNAPSHOT
-
- com.alibaba.smartfox.eclipse.plugin
- eclipse-plugin
- 2017
-
- false
-
-
-
- log4j
- log4j
- 1.2.17
-
-
- com.alibaba.p3c
- p3c-pmd
- 2.0.1
-
-
- org.jetbrains.kotlin
- kotlin-stdlib-jdk8
-
-
- com.google.guava
- guava
- 20.0
-
-
-
- src/main/kotlin
-
-
- org.jetbrains.kotlin
- kotlin-maven-plugin
- ${kotlin.version}
-
-
-
- compile
- compile
-
- compile
-
-
-
-
- test-compile
- test-compile
-
- test-compile
-
-
-
-
-
- org.apache.maven.plugins
- maven-dependency-plugin
- 3.1.1
-
- true
- false
- ${project.build.directory}/lib
-
- p2.eclipse-plugin,apex
- com.alibaba.smartfox.eclipse.plugin
-
- false
-
-
-
- get-dependencies
- process-sources
-
- copy-dependencies
-
-
-
-
-
-
-
-
-
- org.eclipse.m2e
- lifecycle-mapping
- 1.0.0
-
-
-
-
-
-
- org.apache.maven.plugins
-
-
- maven-dependency-plugin
-
- [0,)
-
- copy-dependencies
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/QuickFix.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/QuickFix.kt
deleted file mode 100644
index 51e02aa52..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/QuickFix.kt
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse
-
-import com.alibaba.p3c.pmd.lang.java.rule.constant.UpperEllRule
-import com.alibaba.p3c.pmd.lang.java.rule.oop.EqualsAvoidNullRule
-import com.alibaba.smartfox.eclipse.ui.InspectionResults
-import com.alibaba.smartfox.eclipse.util.getRule
-import com.google.common.io.Files
-import org.eclipse.core.resources.IFile
-import org.eclipse.core.resources.IMarker
-import org.eclipse.core.runtime.NullProgressMonitor
-import org.eclipse.ltk.core.refactoring.TextFileChange
-import org.eclipse.text.edits.ReplaceEdit
-import org.eclipse.ui.IMarkerResolution
-import org.eclipse.ui.IMarkerResolutionGenerator
-import java.nio.charset.Charset
-
-/**
- *
- *
- * @author caikang
- * @date 2017/06/14
- */
-class QuickFixGenerator : IMarkerResolutionGenerator {
- override fun getResolutions(marker: IMarker): Array {
- if (!marker.exists()) {
- return emptyArray()
- }
- val rule = marker.getRule()
- val quickFix = quickFixes[rule.name] ?: return emptyArray()
- return arrayOf(quickFix)
- }
-
- companion object {
- val quickFixes = mapOf(UpperEllRule::class.java.simpleName to UpperEllQuickFix,
- EqualsAvoidNullRule::class.java.simpleName to EqualsAvoidNullQuickFix)
- }
-}
-
-interface RunWithoutViewRefresh : IMarkerResolution {
- fun run(marker: IMarker, refresh: Boolean)
-
- override fun run(marker: IMarker) {
- run(marker, true)
- }
-}
-
-abstract class BaseQuickFix : RunWithoutViewRefresh {
- override fun run(marker: IMarker, refresh: Boolean) {
- if (!marker.exists()) {
- return
- }
- val file = marker.resource as IFile
- doRun(marker, file)
- marker.delete()
- if (refresh) {
- InspectionResults.removeMarker(marker)
- }
- }
-
- abstract fun doRun(marker: IMarker, file: IFile)
-}
-
-object UpperEllQuickFix : BaseQuickFix() {
- override fun doRun(marker: IMarker, file: IFile) {
- val offset = marker.getAttribute(IMarker.CHAR_START, 0)
- val end = marker.getAttribute(IMarker.CHAR_END, 0)
- val content = Files.toString(file.rawLocation.toFile(), Charset.forName(file.charset))
- val replaceString = content.substring(offset, end + 1).replace("l", "L")
- val edit = ReplaceEdit(offset, replaceString.length, replaceString)
- val change = TextFileChange("", file)
- change.edit = edit
- change.perform(NullProgressMonitor())
- }
-
- override fun getLabel(): String {
- return "Replace 'l' to 'L'."
- }
-
-}
-
-object EqualsAvoidNullQuickFix : BaseQuickFix() {
- val equalsName = ".equals("
-
- override fun doRun(marker: IMarker, file: IFile) {
- val offset = marker.getAttribute(IMarker.CHAR_START, 0)
- val end = marker.getAttribute(IMarker.CHAR_END, 0)
- val content = Files.toString(file.rawLocation.toFile(), Charset.forName(file.charset))
- val string = content.substring(offset, end)
- val list = string.split(equalsName).filterNotNull()
- if (list.size != 2) {
- return
- }
- val replace = "${list[1].substringBeforeLast(')')}$equalsName${list[0]})"
- val edit = ReplaceEdit(offset, string.length, replace)
- val change = TextFileChange("", file)
- change.edit = edit
- change.perform(NullProgressMonitor())
- }
-
- override fun getLabel(): String {
- return "Flip equals."
- }
-
-}
\ No newline at end of file
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/SmartfoxActivator.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/SmartfoxActivator.kt
deleted file mode 100644
index 4895aa0b6..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/SmartfoxActivator.kt
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse
-
-import com.alibaba.p3c.pmd.I18nResources
-import net.sourceforge.pmd.Rule
-import net.sourceforge.pmd.RuleSetFactory
-import net.sourceforge.pmd.RuleSets
-import org.apache.log4j.Logger
-import org.eclipse.core.runtime.IStatus
-import org.eclipse.core.runtime.Status
-import org.eclipse.jface.dialogs.MessageDialog
-import org.eclipse.jface.resource.ImageDescriptor
-import org.eclipse.swt.graphics.Image
-import org.eclipse.swt.widgets.Display
-import org.eclipse.ui.plugin.AbstractUIPlugin
-import org.osgi.framework.BundleContext
-import java.util.Locale
-
-/**
- * @author caikang
- * @date 2017/06/14
- */
-class SmartfoxActivator : AbstractUIPlugin() {
-
- init {
- aDefault = this
- }
-
- private val logger = Logger.getLogger(javaClass)!!
- lateinit var ruleSets: RuleSets
- private val localeKey = "p3c.locale"
-
- lateinit var ruleMap: Map
-
- @Throws(Exception::class) override fun start(context: BundleContext) {
- super.start(context)
- I18nResources.changeLanguage(locale)
- ruleSets = createRuleSets()
- ruleMap = ruleSets.allRules.associateBy {
- it.name
- }
- }
-
- @Throws(Exception::class) override fun stop(context: BundleContext?) {
- aDefault = null
- super.stop(context)
- }
-
-
- fun getImage(key: String, iconPath: String = key): Image {
- val registry = imageRegistry
- var image: Image? = registry.get(key)
- if (image == null) {
- val descriptor = getImageDescriptor(iconPath)
- registry.put(key, descriptor)
- image = registry.get(key)
- }
-
- return image!!
- }
-
- val locale: String
- get() {
- val language = preferenceStore.getString(localeKey)
- if (language.isNullOrBlank()) {
- val lang = Locale.getDefault().language
- return if (lang != Locale.ENGLISH.language && lang != Locale.CHINESE.language) {
- Locale.ENGLISH.language
- } else Locale.getDefault().language
- }
-
- return language
- }
-
- fun toggleLocale() {
- val lang = if (Locale.ENGLISH.language == locale) Locale.CHINESE.language else Locale.ENGLISH.language
- preferenceStore.setValue(localeKey, lang)
- }
-
- fun getRule(rule: String): Rule {
- return ruleMap[rule]!!
- }
-
- fun showError(message: String, t: Throwable) {
- logError(message, t)
- Display.getDefault().syncExec {
- MessageDialog.openError(Display.getCurrent().activeShell, "错误", message + "\n" + t.toString())
- }
- }
-
- fun logError(message: String, t: Throwable) {
- log.log(Status(IStatus.ERROR, bundle.symbolicName, 0, message + t.message, t))
- logger.error(message, t)
- }
-
- fun logError(status: IStatus) {
- log.log(status)
- logger.error(status.message, status.exception)
- }
-
- fun logInformation(message: String) {
- log.log(Status(IStatus.INFO, bundle.symbolicName, 0, message, null))
- }
-
- fun logWarn(message: String) {
- log.log(Status(IStatus.WARNING, bundle.symbolicName, 0, message, null))
- }
-
- companion object {
- // The plug-in ID
- val PLUGIN_ID = "com.alibaba.smartfox.eclipse.plugin"
-
- var aDefault: SmartfoxActivator? = null
- private set
-
- val instance: SmartfoxActivator get() = aDefault!!
-
- fun getImageDescriptor(path: String): ImageDescriptor {
- return AbstractUIPlugin.imageDescriptorFromPlugin(PLUGIN_ID, path)
- }
-
- fun createRuleSets(): RuleSets {
- val ruleSetFactory = RuleSetFactory()
- return ruleSetFactory.createRuleSets("java-ali-pmd,vm-ali-other")
- }
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/handler/CodeAnalysisHandler.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/handler/CodeAnalysisHandler.kt
deleted file mode 100644
index f2730a2fd..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/handler/CodeAnalysisHandler.kt
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.handler
-
-import com.alibaba.smartfox.eclipse.job.CodeAnalysis.processResources
-import com.alibaba.smartfox.eclipse.message.P3cBundle
-import com.google.common.collect.Sets
-import org.apache.log4j.Logger
-import org.eclipse.core.commands.AbstractHandler
-import org.eclipse.core.commands.ExecutionEvent
-import org.eclipse.core.commands.ExecutionException
-import org.eclipse.core.resources.IFile
-import org.eclipse.core.resources.IResource
-import org.eclipse.core.resources.IResourceVisitor
-import org.eclipse.core.runtime.IAdaptable
-import org.eclipse.jface.viewers.IStructuredSelection
-import org.eclipse.ui.IFileEditorInput
-import org.eclipse.ui.IWorkingSet
-import org.eclipse.ui.commands.IElementUpdater
-import org.eclipse.ui.handlers.HandlerUtil
-import org.eclipse.ui.menus.UIElement
-import org.eclipse.ui.part.EditorPart
-import org.eclipse.ui.part.ViewPart
-
-/**
- * @author caikang
- * @date 2016/12/27
- */
-open class CodeAnalysisHandler : AbstractHandler(), IElementUpdater {
- override fun updateElement(element: UIElement, parameters: MutableMap?) {
- val text = P3cBundle.getMessage("com.alibaba.smartfox.eclipse.handler.CodeAnalysisHandler")
- element.setText(text)
- element.setTooltip(text)
- }
-
- @Throws(ExecutionException::class)
- override fun execute(executionEvent: ExecutionEvent): Any? {
- val selection = HandlerUtil.getCurrentSelectionChecked(executionEvent)
- val part = HandlerUtil.getActivePart(executionEvent)
- if (part is ViewPart) {
- if (selection is IStructuredSelection) {
- processForMutiFiles(selection)
- }
- } else if (part is EditorPart) {
- val editorInput = HandlerUtil.getActiveEditorInput(executionEvent)
- if (editorInput is IFileEditorInput) {
- processResources(setOf(editorInput.file))
- }
- }
- return null
- }
-
- private fun processForMutiFiles(selection: IStructuredSelection) {
- val resources = getSelectionResources(selection)
- processResources(resources)
- }
-
- private fun getSelectionResources(selection: IStructuredSelection): MutableSet {
- val resources = mutableSetOf()
- selection.toList().forEach {
- when (it) {
- is IWorkingSet -> it.elements.mapTo(resources) { it.getAdapter(IResource::class.java) as IResource }
- is IAdaptable -> {
- val file = it.getAdapter(IResource::class.java) as? IResource ?: return@forEach
- resources.add(file)
- }
- else -> log.warn("The selected object is not adaptable : ${it.toString()}")
- }
- }
- return resources
- }
-
-
- companion object {
- private val log = Logger.getLogger(CodeAnalysisHandler::class.java)
- }
-}
-
-class FileCollectVisitor : IResourceVisitor {
- val fileSet = Sets.newLinkedHashSet()!!
-
- override fun visit(resource: IResource?): Boolean {
- if (resource == null) {
- return false
- }
- val file = resource.getAdapter(IFile::class.java) as? IFile ?: return true
- if (file.exists() && (file.fileExtension == "java" || file.fileExtension == "vm")) {
- fileSet.add(file)
- }
- return false
- }
-}
\ No newline at end of file
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/handler/SwitchLanguageHandler.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/handler/SwitchLanguageHandler.kt
deleted file mode 100644
index e12ba128f..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/handler/SwitchLanguageHandler.kt
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.handler
-
-import com.alibaba.smartfox.eclipse.SmartfoxActivator
-import com.alibaba.smartfox.eclipse.message.P3cBundle
-import org.eclipse.core.commands.AbstractHandler
-import org.eclipse.core.commands.ExecutionEvent
-import org.eclipse.jface.dialogs.MessageDialog
-import org.eclipse.ui.PlatformUI
-import org.eclipse.ui.commands.IElementUpdater
-import org.eclipse.ui.menus.UIElement
-
-/**
- *
- *
- * @author caikang
- * @date 2017/06/21
- */
-class SwitchLanguageHandler : AbstractHandler(), IElementUpdater {
- val handlerKey = "com.alibaba.smartfox.eclipse.handler.SwitchLanguageHandler"
- val textKey = "$handlerKey.text.cur_"
-
- override fun execute(executionEvent: ExecutionEvent): Any? {
- SmartfoxActivator.instance.toggleLocale()
- if (!MessageDialog.openConfirm(null, "Tips",
- P3cBundle.getMessage("$handlerKey.success.${SmartfoxActivator.instance.locale}"))) {
- return null
- }
- PlatformUI.getWorkbench().restart()
- return null
- }
-
- override fun updateElement(element: UIElement, parameters: MutableMap?) {
- val text = P3cBundle.getMessage("$textKey${SmartfoxActivator.instance.locale}")
- element.setText(text)
- element.setTooltip(text)
- }
-}
\ No newline at end of file
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/CodeAnalysis.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/CodeAnalysis.kt
deleted file mode 100644
index 166c8e37e..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/CodeAnalysis.kt
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.job
-
-import com.alibaba.p3c.pmd.lang.java.util.GeneratedCodeUtils
-import com.alibaba.smartfox.eclipse.SmartfoxActivator
-import com.alibaba.smartfox.eclipse.handler.CodeAnalysisHandler
-import com.alibaba.smartfox.eclipse.handler.FileCollectVisitor
-import com.alibaba.smartfox.eclipse.ui.InspectionResultView
-import com.alibaba.smartfox.eclipse.ui.InspectionResults
-import com.alibaba.smartfox.eclipse.ui.MarkerViolation
-import com.alibaba.smartfox.eclipse.util.MarkerUtil
-import com.google.common.io.Files
-import net.sourceforge.pmd.PMDConfiguration
-import net.sourceforge.pmd.PMDException
-import net.sourceforge.pmd.Report
-import net.sourceforge.pmd.RuleContext
-import net.sourceforge.pmd.RuleViolation
-import net.sourceforge.pmd.SourceCodeProcessor
-import org.apache.log4j.Logger
-import org.eclipse.core.resources.IFile
-import org.eclipse.core.resources.IResource
-import org.eclipse.core.runtime.IProgressMonitor
-import org.eclipse.core.runtime.IStatus
-import org.eclipse.core.runtime.Status
-import org.eclipse.core.runtime.SubMonitor
-import org.eclipse.core.runtime.jobs.Job
-import java.io.IOException
-import java.io.StringReader
-import java.nio.charset.Charset
-
-/**
- *
- *
- * @author caikang
- * @date 2017/06/14
- */
-object CodeAnalysis {
- private val log = Logger.getLogger(CodeAnalysisHandler::class.java)
-
- fun processResources(resources: Set) {
- InspectionResultView.activeViews()
- val job = object : Job("P3C Code Analysis") {
- override fun run(monitor: IProgressMonitor): IStatus {
- val fileVisitor = FileCollectVisitor()
- monitor.setTaskName("Collect files")
- resources.forEach {
- if (monitor.isCanceled) {
- return@run Status.CANCEL_STATUS
- }
- if (it.isAccessible) {
- it.accept(fileVisitor)
- }
- }
- if (monitor.isCanceled) {
- return Status.CANCEL_STATUS
- }
- val subMonitor = SubMonitor.convert(monitor, "Analysis files", fileVisitor.fileSet.size)
- monitor.setTaskName("Analysis files")
- fileVisitor.fileSet.forEach { iFile ->
- if (monitor.isCanceled) {
- return@run Status.CANCEL_STATUS
- }
- MarkerUtil.removeAllMarkers(iFile)
- monitor.subTask(iFile.fullPath.toPortableString())
- val markers = processFileToMakers(iFile, monitor)
- subMonitor.newChild(1)
- InspectionResults.updateFileViolations(iFile, markers)
- }
- return Status.OK_STATUS
- }
- }
- job.apply {
- isUser = true
- isSystem = false
- priority = Job.INTERACTIVE
- rule = P3cMutex
- schedule()
- }
- }
-
- fun processFileToMakers(file: IFile, monitor: IProgressMonitor): List {
- file.refreshLocal(IResource.DEPTH_ZERO, monitor)
- val ruleViolations = processFile(file)
-
- MarkerUtil.removeAllMarkers(file)
- return ruleViolations.map {
- MarkerViolation(MarkerUtil.addMarker(file, it), it)
- }
- }
-
- private fun processFile(file: IFile): List {
- val configuration = PMDConfiguration()
- configuration.setSourceEncoding(file.charset ?: Charsets.UTF_8.name())
- configuration.inputPaths = file.fullPath.toPortableString()
- val ctx = RuleContext()
- ctx.setAttribute("eclipseFile", file)
- val niceFileName = configuration.inputPaths
- val report = Report.createReport(ctx, niceFileName)
- SmartfoxActivator.instance.ruleSets.start(ctx)
- val processor = SourceCodeProcessor(configuration)
- try {
- ctx.languageVersion = null
- val content = Files.toString(file.rawLocation.toFile(), Charset.forName(file.charset))
- if (!GeneratedCodeUtils.isGenerated(content)) {
- processor.processSourceCode(StringReader(content), SmartfoxActivator.instance.ruleSets, ctx)
- }
- } catch (pmde: PMDException) {
- log.debug("Error while processing file: " + niceFileName, pmde.cause)
- report.addError(Report.ProcessingError(pmde, niceFileName))
- } catch (ioe: IOException) {
- log.error("Unable to read source file: " + niceFileName, ioe)
- } catch (re: RuntimeException) {
- log.error("RuntimeException while processing file: " + niceFileName, re)
- } finally {
- SmartfoxActivator.instance.ruleSets.end(ctx)
- }
- return report.toList()
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/RulePriority.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/RulePriority.kt
deleted file mode 100644
index 260ffc15c..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/RulePriority.kt
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.pmd
-
-enum class RulePriority(val priority: Int, val title: String) {
-
- Blocker(1, "Blocker"), Critical(2, "Critical"), Major(3, "Major");
-
- override fun toString(): String {
- return title
- }
-
- companion object {
- fun valueOf(priority: Int): RulePriority {
- try {
- return RulePriority.values()[priority - 1]
- } catch (e: ArrayIndexOutOfBoundsException) {
- return Major
- }
- }
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AbstractEclipseRule.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AbstractEclipseRule.kt
deleted file mode 100644
index cdae0301b..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AbstractEclipseRule.kt
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.pmd.rule
-
-import com.alibaba.smartfox.eclipse.message.P3cBundle
-import net.sourceforge.pmd.Rule
-import net.sourceforge.pmd.RuleContext
-import net.sourceforge.pmd.RuleViolation
-import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit
-import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule
-import org.eclipse.core.resources.IFile
-import org.eclipse.core.runtime.NullProgressMonitor
-import org.eclipse.jdt.core.ICompilationUnit
-import org.eclipse.jdt.core.IProblemRequestor
-import org.eclipse.jdt.core.JavaCore
-import org.eclipse.jdt.core.JavaModelException
-import org.eclipse.jdt.core.WorkingCopyOwner
-import org.eclipse.jdt.core.compiler.IProblem
-import org.eclipse.jdt.core.dom.ASTNode
-import org.eclipse.jdt.core.dom.ASTVisitor
-import org.eclipse.jdt.core.dom.CompilationUnit
-import java.util.MissingResourceException
-
-/**
- * @author caikang
- * @date 2016/12/26
- */
-abstract class AbstractEclipseRule : AbstractJavaRule() {
-
- open fun getErrorMessage(): String {
- return message
- }
-
- override fun visit(node: ASTCompilationUnit, data: Any): Any? {
- val result = super.visit(node, data)
- val ruleContext = data as RuleContext
- val file = ruleContext.getAttribute("eclipseFile") as? IFile ?: return result
- val compilationUnit = JavaCore.createCompilationUnitFrom(file) ?: return data
- try {
- val requestor = object : IProblemRequestor {
- override fun acceptProblem(problem: IProblem) {}
-
- override fun beginReporting() {}
-
- override fun endReporting() {}
-
- override fun isActive(): Boolean {
- return true
- }
- }
- val workingCopy = compilationUnit.getWorkingCopy(null)
- val ast = workingCopy.reconcile(JLS8, ICompilationUnit.FORCE_PROBLEM_DETECTION
- or ICompilationUnit.ENABLE_BINDINGS_RECOVERY or ICompilationUnit.ENABLE_STATEMENTS_RECOVERY,
- object : WorkingCopyOwner() {
- override fun getProblemRequestor(workingCopy: ICompilationUnit?): IProblemRequestor {
- return requestor
- }
- }, NullProgressMonitor()) ?: return data
- ast.accept(getVisitor(ast, ruleContext))
-
- } catch (e: JavaModelException) {
- throw RuntimeException(e)
- }
-
- return data
- }
-
- override fun setDescription(description: String?) {
- try {
- super.setDescription(P3cBundle.getMessage(description ?: ""))
- } catch (e: MissingResourceException) {
- super.setMessage(description)
- }
-
- }
-
- override fun setMessage(message: String) {
- try {
- super.setMessage(P3cBundle.getMessage(message))
- } catch (e: MissingResourceException) {
- super.setMessage(message)
- }
-
- }
-
-
- protected abstract fun getVisitor(ast: CompilationUnit, ruleContext: RuleContext): ASTVisitor
-
- internal fun addRuleViolation(ruleContext: RuleContext, ast: CompilationUnit, nodeInfo: NodeInfo) {
- val rule = this
- val ruleViolation = object : RuleViolation {
- override fun getRule(): Rule {
- return rule
- }
-
- override fun getDescription(): String {
- return getErrorMessage().trim { it <= ' ' }
- }
-
- override fun isSuppressed(): Boolean {
- return false
- }
-
- override fun getFilename(): String {
- return ruleContext.sourceCodeFilename
- }
-
- override fun getBeginLine(): Int {
- return ast.getLineNumber(nodeInfo.startPosition)
- }
-
- override fun getBeginColumn(): Int {
- return ast.getColumnNumber(nodeInfo.startPosition)
- }
-
- override fun getEndLine(): Int {
- return ast.getLineNumber(nodeInfo.endPosition)
- }
-
- override fun getEndColumn(): Int {
- return ast.getColumnNumber(nodeInfo.endPosition)
- }
-
- override fun getPackageName(): String? {
- return nodeInfo.packageName
- }
-
- override fun getClassName(): String? {
- return nodeInfo.className
- }
-
- override fun getMethodName(): String? {
- return nodeInfo.methodName
- }
-
- override fun getVariableName(): String? {
- return nodeInfo.variableName
- }
-
- override fun toString(): String {
- return rule.toString()
- }
-
-
- }
-
- ruleContext.report.addRuleViolation(ruleViolation)
- }
-
- protected fun violation(rc: RuleContext, node: ASTNode, ast: CompilationUnit) {
- val nodeInfo = NodeInfo()
- nodeInfo.className = ast.javaElement.elementName
- nodeInfo.packageName = ast.`package`.name.fullyQualifiedName
- nodeInfo.startPosition = node.startPosition
- nodeInfo.endPosition = node.startPosition + node.length
-
- addRuleViolation(rc, ast, nodeInfo)
- }
-
- inner class NodeInfo {
- internal var packageName: String? = null
- internal var className: String? = null
- internal var methodName: String? = null
- internal var variableName: String? = null
- internal var startPosition: Int = 0
- internal var endPosition: Int = 0
- }
-
- companion object {
- val JLS8 = 8
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AvoidAccessStaticViaInstanceRule.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AvoidAccessStaticViaInstanceRule.kt
deleted file mode 100644
index 44d7fd7ef..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AvoidAccessStaticViaInstanceRule.kt
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.pmd.rule
-
-import net.sourceforge.pmd.RuleContext
-import org.eclipse.jdt.core.dom.ASTVisitor
-import org.eclipse.jdt.core.dom.ClassInstanceCreation
-import org.eclipse.jdt.core.dom.CompilationUnit
-import org.eclipse.jdt.core.dom.FieldAccess
-import org.eclipse.jdt.core.dom.IVariableBinding
-import org.eclipse.jdt.core.dom.MethodInvocation
-import org.eclipse.jdt.core.dom.Modifier
-import org.eclipse.jdt.core.dom.QualifiedName
-import org.eclipse.jdt.core.dom.SimpleName
-import org.eclipse.jdt.core.dom.VariableDeclarationFragment
-
-/**
- * @author caikang
- * @date 2016/12/27
- */
-class AvoidAccessStaticViaInstanceRule : AbstractEclipseRule() {
- override fun getVisitor(ast: CompilationUnit, ruleContext: RuleContext): ASTVisitor {
- return object : ASTVisitor() {
- override fun visit(node: QualifiedName?): Boolean {
- val parent = node!!.parent
- if (parent !is MethodInvocation && parent !is VariableDeclarationFragment) {
- return false
- }
- val name = node.name
- val binding = name.resolveBinding()
- if (binding !is IVariableBinding || binding.getModifiers() and Modifier.STATIC == 0) {
- return true
- }
- val qualifier = node.qualifier
- val typeBinding = qualifier.resolveTypeBinding()
- if (qualifier.isSimpleName) {
- when (parent) {
- is MethodInvocation -> {
- val methodBinding = parent.resolveMethodBinding()
- val methodTypeBinding = methodBinding.declaringClass
- if (methodBinding.modifiers and Modifier.STATIC != 0
- && qualifier.fullyQualifiedName != methodTypeBinding.name
- && methodTypeBinding == typeBinding && binding.name != typeBinding.name) {
- violation(ruleContext, parent, ast)
- return false
- }
- }
- else -> {
- }
- }
- if (typeBinding.name != qualifier.fullyQualifiedName) {
- violation(ruleContext, node, ast)
- return false
- }
- }
- if (qualifier.isQualifiedName) {
- val qualifiedName = qualifier as QualifiedName
- if (typeBinding.name != qualifiedName.name.identifier) {
- violation(ruleContext, node, ast)
- return false
- }
- }
- return true
- }
-
- override fun visit(node: FieldAccess): Boolean {
- val variableBinding = node.resolveFieldBinding() ?: return false
- if (variableBinding.modifiers and Modifier.STATIC == 0) {
- return true
- }
- if (node.expression is ClassInstanceCreation) {
- violation(ruleContext, node, ast)
- return true
- }
- return true
- }
-
- override fun visit(node: MethodInvocation?): Boolean {
- val methodBinding = node?.resolveMethodBinding() ?: return false
- if (methodBinding.modifiers and Modifier.STATIC == 0) {
- return true
- }
- if (node.expression is ClassInstanceCreation) {
- violation(ruleContext, node, ast)
- return true
- }
- val expression = node.expression
- if (expression is SimpleName && expression.identifier != expression.resolveTypeBinding().name) {
- violation(ruleContext, node, ast)
- return true
- }
- return true
- }
- }
- }
-
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AvoidUseDeprecationRule.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AvoidUseDeprecationRule.kt
deleted file mode 100644
index 8bd987139..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AvoidUseDeprecationRule.kt
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.pmd.rule
-
-import net.sourceforge.pmd.RuleContext
-import org.eclipse.jdt.core.dom.ASTVisitor
-import org.eclipse.jdt.core.dom.ClassInstanceCreation
-import org.eclipse.jdt.core.dom.CompilationUnit
-import org.eclipse.jdt.core.dom.FieldAccess
-import org.eclipse.jdt.core.dom.IVariableBinding
-import org.eclipse.jdt.core.dom.ImportDeclaration
-import org.eclipse.jdt.core.dom.MethodInvocation
-import org.eclipse.jdt.core.dom.Modifier
-import org.eclipse.jdt.core.dom.QualifiedName
-import org.eclipse.jdt.core.dom.TypeDeclaration
-import org.eclipse.jdt.core.dom.VariableDeclarationFragment
-
-/**
- * @author caikang
- * @date 2016/12/27
- */
-class AvoidUseDeprecationRule : AbstractEclipseRule() {
- override fun getVisitor(ast: CompilationUnit, ruleContext: RuleContext): ASTVisitor {
- return object : ASTVisitor() {
- override fun visit(node: ImportDeclaration?): Boolean {
- if (node!!.resolveBinding() != null && node.resolveBinding().isDeprecated) {
- violation(ruleContext, node, ast)
- }
- return true
- }
-
- override fun visit(node: QualifiedName?): Boolean {
- if (node!!.parent !is MethodInvocation && node.parent !is VariableDeclarationFragment) {
- return false
- }
- val name = node.name
- val binding = name.resolveBinding()
- if (binding !is IVariableBinding || binding.getModifiers() and Modifier.STATIC == 0) {
- return true
- }
- if (binding.isDeprecated()) {
- violation(ruleContext, node, ast)
- return false
- }
- val qualifier = node.qualifier
- val typeBinding = qualifier.resolveTypeBinding()
- if (typeBinding.isDeprecated) {
- violation(ruleContext, node, ast)
- return false
- }
- return true
- }
-
- override fun visit(node: TypeDeclaration?): Boolean {
- val superClass = node!!.superclassType
- if (superClass != null && superClass.resolveBinding().isDeprecated) {
- violation(ruleContext, node, ast)
- return true
- }
- val interfaces = node.resolveBinding().interfaces
- for (tb in interfaces) {
- if (tb.isDeprecated) {
- violation(ruleContext, node, ast)
- return true
- }
- }
- return true
- }
-
- override fun visit(node: FieldAccess?): Boolean {
- val variableBinding = node!!.resolveFieldBinding() ?: return false
- if (variableBinding.isDeprecated) {
- violation(ruleContext, node, ast)
- }
- return true
- }
-
- override fun visit(node: MethodInvocation): Boolean {
- val methodBinding = node.resolveMethodBinding() ?: return false
- if (methodBinding.isDeprecated) {
- violation(ruleContext, node, ast)
- }
- return true
- }
-
- override fun visit(node: ClassInstanceCreation?): Boolean {
- if (node!!.resolveTypeBinding().isDeprecated) {
- violation(ruleContext, node, ast)
- }
- return true
- }
- }
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/MapOrSetKeyShouldOverrideHashCodeEqualsRule.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/MapOrSetKeyShouldOverrideHashCodeEqualsRule.kt
deleted file mode 100644
index 4ea226113..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/MapOrSetKeyShouldOverrideHashCodeEqualsRule.kt
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.pmd.rule
-
-import net.sourceforge.pmd.RuleContext
-import org.eclipse.jdt.core.dom.ASTVisitor
-import org.eclipse.jdt.core.dom.CompilationUnit
-import org.eclipse.jdt.core.dom.ITypeBinding
-import org.eclipse.jdt.core.dom.MethodInvocation
-import org.eclipse.jdt.core.dom.VariableDeclarationStatement
-
-/**
- * @author zenghou.fw
- * @date 2016/12/27
- */
-class MapOrSetKeyShouldOverrideHashCodeEqualsRule : AbstractEclipseRule() {
-
- val methodEquals = "equals"
- val methodHashCode = "hashCode"
- val methodAdd = "add"
- val methodPut = "put"
-
- private val skipJdkPackageJava = "java."
- private val skipJdkPackageJavax = "javax."
-
- override fun getVisitor(ast: CompilationUnit, ruleContext: RuleContext): ASTVisitor {
- return object : ASTVisitor() {
-
- override fun visit(node: VariableDeclarationStatement): Boolean {
- if (!node.type.isParameterizedType) {
- return true
- }
- val typeBinding = node.type.resolveBinding()
- if (isSet(typeBinding) || isMap(typeBinding)) {
- val argumentTypes = typeBinding.typeArguments
- if (argumentTypes != null && argumentTypes.isNotEmpty()) {
- if (!isOverrideEqualsAndHashCode(argumentTypes[0])) {
- violation(ruleContext, node, ast)
- return false
- }
- }
- }
- return true
- }
-
- override fun visit(node: MethodInvocation): Boolean {
- val methodBinding = node.resolveMethodBinding() ?: return false
- val callerType = methodBinding.declaringClass
-
- if (methodAdd == methodBinding.name) {
- if (!isSet(callerType)) {
- return true
- }
- val parameterTypes = methodBinding.parameterTypes
- if (parameterTypes != null && parameterTypes.isNotEmpty()) {
- if (!isOverrideEqualsAndHashCode(parameterTypes[0])) {
- violation(ruleContext, node, ast)
- return false
- }
- }
- return true
- }
- if (methodPut == methodBinding.name) {
- if (!isMap(callerType)) {
- return true
- }
- val parameterTypes = methodBinding.parameterTypes
- if (parameterTypes != null && parameterTypes.isNotEmpty()) {
- if (!isOverrideEqualsAndHashCode(parameterTypes[0])) {
- violation(ruleContext, node, ast)
- return false
- }
- }
- }
- return true
- }
-
- private fun isOverrideEqualsAndHashCode(genericType: ITypeBinding): Boolean {
- val skip = genericType.isEnum || genericType.isInterface || genericType.isArray
- || genericType.isTypeVariable || genericType.isWildcardType
- || genericType.qualifiedName?.startsWith(skipJdkPackageJava) ?: false
- || genericType.qualifiedName?.startsWith(skipJdkPackageJavax) ?: false
- // skip
- if (skip) {
- return true
- }
-
- val methodBindings = genericType.declaredMethods ?: return false
-
- val overrideCount = methodBindings.asSequence().filter {
- //find equals(Object o) and hashCode() with @Override
- methodEquals == it.name || methodHashCode == it.name
- }.filter {
- when (it.name) {
- methodEquals -> {
- val parameterTypes = it.parameterTypes
- parameterTypes != null && parameterTypes.isNotEmpty()
- && Object::class.java.name == parameterTypes[0].qualifiedName
- }
- methodHashCode -> {
- val parameterTypes = it.parameterTypes
- parameterTypes == null || parameterTypes.isEmpty()
- }
- else -> false
- }
- }.count()
- return overrideCount == 2
- }
-
- private fun isSet(typeBinding: ITypeBinding): Boolean {
- return java.util.Set::class.java.name == typeBinding.binaryName
- }
-
- private fun isMap(typeBinding: ITypeBinding): Boolean {
- return java.util.Map::class.java.name == typeBinding.binaryName
- }
- }
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/MissingOverrideAnnotationRule.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/MissingOverrideAnnotationRule.kt
deleted file mode 100644
index 5007be971..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/MissingOverrideAnnotationRule.kt
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.pmd.rule
-
-import com.alibaba.smartfox.eclipse.message.P3cBundle
-import net.sourceforge.pmd.RuleContext
-import org.eclipse.jdt.core.dom.ASTVisitor
-import org.eclipse.jdt.core.dom.CompilationUnit
-import org.eclipse.jdt.core.dom.MethodDeclaration
-import org.eclipse.jdt.internal.compiler.lookup.MethodBinding
-import java.util.Arrays
-import javax.annotation.Generated
-
-/**
- * @author caikang
- * @date 2016/12/24
- */
-class MissingOverrideAnnotationRule : AbstractEclipseRule() {
- override fun getErrorMessage(): String {
- return P3cBundle.getMessage("rule.standalone.MissingOverrideAnnotationRule.error")
- }
-
- override fun getVisitor(ast: CompilationUnit, ruleContext: RuleContext): ASTVisitor {
- return MissingOverrideVisitor(ast, ruleContext)
- }
-
- private inner class MissingOverrideVisitor(private val ast: CompilationUnit,
- private val ruleContext: RuleContext) : ASTVisitor() {
-
- override fun visit(node: MethodDeclaration?): Boolean {
- val methodBinding = node!!.resolveBinding()
- val declaringClass = methodBinding.declaringClass ?: return super.visit(node)
- if (declaringClass.isInterface) {
- return super.visit(node)
- }
- val abs = methodBinding.annotations
- if (abs.any {
- Override::class.java.canonicalName == it.annotationType.binaryName
- }) {
- return super.visit(node)
- }
- try {
- val field = methodBinding.javaClass.getDeclaredField("binding")
- field.isAccessible = true
- val internalBinding = field.get(methodBinding) as MethodBinding
- if (internalBinding.isStatic || !(internalBinding.isImplementing || internalBinding.isOverriding)
- || isGenerated(internalBinding)) {
- return super.visit(node)
- }
- violation(ruleContext, node, ast)
- } catch (e: Exception) {
- e.printStackTrace()
- }
-
- return super.visit(node)
- }
-
- /**
- * skip @Override check for generated code by lombok
- * @param internalBinding
- * @return
- */
- private fun isGenerated(internalBinding: MethodBinding): Boolean {
- val annotationBindings = internalBinding.annotations ?: return false
- return annotationBindings.any {
- it.annotationType != null && Arrays.equals(Generated::class.java.name.toCharArray(),
- it.annotationType.readableName())
- }
- }
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/AllRulesPreferencePage.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/AllRulesPreferencePage.kt
deleted file mode 100644
index c7acc8e0d..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/AllRulesPreferencePage.kt
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.ui
-
-import org.eclipse.jface.preference.PreferencePage
-import org.eclipse.swt.widgets.Composite
-import org.eclipse.swt.widgets.Control
-import org.eclipse.ui.IWorkbench
-import org.eclipse.ui.IWorkbenchPreferencePage
-
-/**
- *
- * @author caikang
- * @date 2017/09/01
- */
-class AllRulesPreferencePage : PreferencePage(), IWorkbenchPreferencePage {
- override fun init(parent: IWorkbench?) {
- }
-
- override fun createContents(parent: Composite): Control {
- return AllRulesView(parent).content
- }
-}
\ No newline at end of file
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/AllRulesView.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/AllRulesView.kt
deleted file mode 100644
index b7578d441..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/AllRulesView.kt
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.ui
-
-import com.alibaba.smartfox.eclipse.SmartfoxActivator
-import org.eclipse.swt.SWT
-import org.eclipse.swt.layout.FillLayout
-import org.eclipse.swt.widgets.Composite
-import org.eclipse.swt.widgets.List
-
-
-/**
- *
- * @author caikang
- * @date 2017/09/01
- */
-class AllRulesView(parent: Composite) {
- val content = Composite(parent, SWT.NONE)
-
- private val ruleList = SmartfoxActivator.instance.ruleSets.allRules.toList()
-
- init {
- content.layout = FillLayout()
- val list = List(content, SWT.BORDER or SWT.SINGLE or SWT.V_SCROLL or SWT.PUSH or SWT.H_SCROLL)
- ruleList.forEach {
- list.add(it.message)
- }
- val ruleDetail = RuleDetailComposite(content, SWT.PUSH)
- list.addListener(SWT.Selection) {
- val index = list.selectionIndex
- val rule = ruleList.getOrNull(index) ?: return@addListener
- ruleDetail.refresh(rule)
- }
- list.select(0)
- }
-}
\ No newline at end of file
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultTreeContentProvider.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultTreeContentProvider.kt
deleted file mode 100644
index 26e541a04..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultTreeContentProvider.kt
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.ui
-
-import org.eclipse.jface.viewers.ITreeContentProvider
-import org.eclipse.jface.viewers.Viewer
-
-/**
- *
- *
- * @author caikang
- * @date 2017/06/08
- */
-object InspectionResultTreeContentProvider : ITreeContentProvider {
- private lateinit var input: InspectionResults
-
- override fun getParent(element: Any?): Any {
- return input
- }
-
- override fun hasChildren(element: Any?): Boolean {
- return element is InspectionResults || element is LevelViolations || element is RuleViolations
- || element is FileMarkers
- }
-
- override fun getChildren(parentElement: Any?): Array {
- if (parentElement is InspectionResults) {
- return parentElement.errors.toTypedArray()
- }
- if (parentElement is LevelViolations) {
- return parentElement.rules.toTypedArray()
- }
- if (parentElement is RuleViolations) {
- return parentElement.files.toTypedArray()
- }
- if (parentElement is FileMarkers) {
- return parentElement.markers.toTypedArray()
- }
- return emptyArray()
- }
-
- override fun getElements(inputElement: Any?): Array {
- return input.errors.toTypedArray()
- }
-
- override fun inputChanged(viewer: Viewer?, oldInput: Any?, newInput: Any?) {
- if (newInput == null) {
- return
- }
- this.input = newInput as InspectionResults
- }
-
- override fun dispose() {
- }
-}
\ No newline at end of file
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultTreeLabelProvider.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultTreeLabelProvider.kt
deleted file mode 100644
index 286ce0a83..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultTreeLabelProvider.kt
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.ui
-
-import com.alibaba.smartfox.eclipse.SmartfoxActivator
-import com.alibaba.smartfox.eclipse.pmd.RulePriority
-import org.eclipse.jface.viewers.LabelProvider
-import org.eclipse.swt.graphics.Image
-
-/**
- *
- *
- * @author caikang
- * @date 2017/06/08
- */
-object InspectionResultTreeLabelProvider : LabelProvider() {
- override fun getImage(element: Any?): Image? {
- if (element is LevelViolations) {
- val imageName = when (element.level) {
- RulePriority.Blocker.title, RulePriority.Critical.title -> "${element.level}.gif".toLowerCase()
- else -> "${element.level}.png".toLowerCase()
- }
- return SmartfoxActivator.instance.getImage("icons/view/$imageName")
- }
- if (element is FileMarkers) {
- if (element.file.fullPath.toPortableString().endsWith("java")) {
- return SmartfoxActivator.instance.getImage("icons/view/class_obj.png")
- }
- return SmartfoxActivator.instance.getImage("icons/view/file_obj.png")
- }
- return null
- }
-
- override fun getText(element: Any?): String {
- if (element is LevelViolations) {
- return "${element.level} (${element.count} Violations)"
- }
- if (element is RuleViolations) {
- val rule = SmartfoxActivator.instance.getRule(element.rule)
- return "${rule.message} (${element.count} Violations)"
- }
- if (element is FileMarkers) {
- return element.file.fullPath.toPortableString().substringAfterLast("/") +
- " (${element.markers.size} Violations)"
- }
- if (element is MarkerViolation) {
- val desc = element.violation.description
- return "$desc (at line ${element.violation.beginLine})"
- }
- return element.toString()
- }
-}
\ No newline at end of file
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultView.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultView.kt
deleted file mode 100644
index ac5dbcdc3..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResultView.kt
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.ui
-
-import com.alibaba.smartfox.eclipse.SmartfoxActivator
-import com.alibaba.smartfox.eclipse.job.P3cMutex
-import com.alibaba.smartfox.eclipse.util.MarkerUtil
-import org.eclipse.core.resources.IFile
-import org.eclipse.core.resources.IMarker
-import org.eclipse.core.runtime.IProgressMonitor
-import org.eclipse.core.runtime.IStatus
-import org.eclipse.core.runtime.Status
-import org.eclipse.core.runtime.jobs.Job
-import org.eclipse.jface.action.Action
-import org.eclipse.jface.action.Separator
-import org.eclipse.jface.util.OpenStrategy
-import org.eclipse.jface.viewers.ISelection
-import org.eclipse.jface.viewers.IStructuredSelection
-import org.eclipse.jface.viewers.ITreeSelection
-import org.eclipse.jface.viewers.TreeViewer
-import org.eclipse.swt.SWT
-import org.eclipse.swt.layout.FillLayout
-import org.eclipse.swt.widgets.Composite
-import org.eclipse.swt.widgets.Display
-import org.eclipse.ui.IWorkbenchPage
-import org.eclipse.ui.OpenAndLinkWithEditorHelper
-import org.eclipse.ui.PartInitException
-import org.eclipse.ui.PlatformUI
-import org.eclipse.ui.ide.IDE
-import org.eclipse.ui.ide.ResourceUtil
-import org.eclipse.ui.internal.views.markers.MarkerSupportInternalUtilities
-import org.eclipse.ui.part.ViewPart
-import org.eclipse.ui.texteditor.ITextEditor
-import java.util.HashSet
-
-/**
- *
- *
- * @author caikang
- * @date 2017/06/08
- */
-class InspectionResultView : ViewPart() {
- lateinit var treeViewer: TreeViewer
-
- private val quickFixAction = QuickFixAction(this)
-
- override fun setFocus() {
- treeViewer.control.setFocus()
- }
-
- override fun createPartControl(parent: Composite) {
- parent.layout = FillLayout()
- treeViewer = TreeViewer(parent, SWT.MULTI or SWT.H_SCROLL or SWT.V_SCROLL)
- treeViewer.setUseHashlookup(true)
- treeViewer.contentProvider = InspectionResultTreeContentProvider
- treeViewer.labelProvider = InspectionResultTreeLabelProvider
- treeViewer.input = InspectionResults
-
- InspectionResults.view = this
-
- addDoubleClickListener()
-
- addSelectionChangedListener()
-
- initToolBar()
-
- addLinkWithEditorSupport()
- site.selectionProvider = treeViewer
- }
-
- fun clear() {
- InspectionResults.clear()
- refreshView(InspectionResults)
- }
-
- fun refreshView(input: InspectionResults) {
- Display.getDefault().asyncExec {
- treeViewer.refresh(input, true)
- contentDescription = input.contentDescription
- }
- }
-
- private fun addSelectionChangedListener() {
- treeViewer.addSelectionChangedListener inner@ {
- val selection = it.selection as? IStructuredSelection ?: return@inner
- val item = selection.firstElement ?: return@inner
- val ruleDetailView = RuleDetailView.showAndGetView()
- when (item) {
- is MarkerViolation -> {
- ruleDetailView.refresh(item.violation.rule)
- quickFixAction.updateFileMarkers(listOf(FileMarkers(item.marker.resource as IFile, listOf(item))))
- }
- is FileMarkers -> {
- ruleDetailView.refresh(item.markers.first().violation.rule)
- quickFixAction.updateFileMarkers(listOf(item))
- }
- is RuleViolations -> {
- ruleDetailView.refresh(SmartfoxActivator.instance.getRule(item.rule))
- quickFixAction.updateFileMarkers(item.files)
- }
- else -> {
- quickFixAction.updateFileMarkers(emptyList())
- }
- }
- }
- }
-
- private fun initToolBar() {
- val bars = viewSite.actionBars
- val tm = bars.toolBarManager
-
- val clearAction = object : Action("Clear Markers") {
- override fun run() {
- val job = object : Job("Clear Markers") {
- override fun run(monitor: IProgressMonitor): IStatus {
- if (monitor.isCanceled) {
- Status.CANCEL_STATUS
- }
- clear()
- return Status.OK_STATUS
- }
- }
- job.rule = P3cMutex
- job.schedule()
- }
- }
-
- clearAction.imageDescriptor = SmartfoxActivator.getImageDescriptor("icons/actions/clear.png")
-
- tm.add(Separator("Markers"))
- tm.add(clearAction)
-
- tm.add(Separator("FilterGroup"))
- tm.add(quickFixAction)
- }
-
- private fun addLinkWithEditorSupport() {
- object : OpenAndLinkWithEditorHelper(treeViewer) {
- override fun activate(selection: ISelection) {
- val currentMode = OpenStrategy.getOpenMethod()
- try {
- OpenStrategy.setOpenMethod(OpenStrategy.DOUBLE_CLICK)
- openSelectedMarkers()
- } finally {
- OpenStrategy.setOpenMethod(currentMode)
- }
- }
-
- override fun linkToEditor(selection: ISelection?) {
- }
-
- override fun open(selection: ISelection, activate: Boolean) {
- val structured = selection as ITreeSelection
- val element = structured.firstElement as? MarkerViolation ?: return
- val page = site.page
- if (element.marker.exists()) {
- openMarkerInEditor(element.marker, page)
- return
- }
- val file = element.marker.resource as IFile
- val editor = IDE.openEditor(page, file) as ITextEditor
- editor.selectAndReveal(MarkerUtil.getAbsoluteRange(file, element.violation).start, 0)
- }
- }
- }
-
- internal fun openSelectedMarkers() {
- val markers = getOpenableMarkers()
- for (marker in markers) {
- val page = site.page
- openMarkerInEditor(marker, page)
- }
- }
-
- private fun getOpenableMarkers(): Array {
- val structured = treeViewer.selection as ITreeSelection
- val elements = structured.iterator()
- val result = HashSet()
-
- while (elements.hasNext()) {
- val marker = elements.next() as? IMarker ?: return emptyArray()
- result.add(marker)
- }
- return result.toTypedArray()
- }
-
-
- fun openMarkerInEditor(marker: IMarker?, page: IWorkbenchPage) {
- val editor = page.activeEditor
- if (editor != null) {
- val input = editor.editorInput
- val file = ResourceUtil.getFile(input)
- if (file != null) {
- if (marker!!.resource == file && OpenStrategy.activateOnOpen()) {
- page.activate(editor)
- }
- }
- }
-
- if (marker != null && marker.resource is IFile) {
- try {
- IDE.openEditor(page, marker, OpenStrategy.activateOnOpen())
- } catch (e: PartInitException) {
- MarkerSupportInternalUtilities.showViewError(e)
- }
-
- }
- }
-
- private fun addDoubleClickListener() {
- treeViewer.addDoubleClickListener({ event ->
- val selection = event.selection
- if (selection !is ITreeSelection || selection.size() != 1) {
- return@addDoubleClickListener
- }
- val obj = selection.firstElement
- if (treeViewer.isExpandable(obj)) {
- treeViewer.setExpandedState(obj, !treeViewer.getExpandedState(obj))
- }
- })
- }
-
- companion object {
- val viewId = "com.alibaba.smartfox.eclipse.ui.InspectionResultView"
-
- fun activeViews() {
- PlatformUI.getWorkbench().activeWorkbenchWindow.activePage.showView(viewId)
- RuleDetailView.showAndGetView()
- }
-
- fun getView(): InspectionResultView {
- return PlatformUI.getWorkbench().activeWorkbenchWindow.activePage.findView(viewId) as InspectionResultView
- }
- }
-}
-
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResults.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResults.kt
deleted file mode 100644
index 3e1482081..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResults.kt
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.ui
-
-import com.alibaba.smartfox.eclipse.pmd.RulePriority
-import com.alibaba.smartfox.eclipse.util.MarkerUtil
-import org.eclipse.core.resources.IFile
-import org.eclipse.core.resources.IMarker
-
-/**
- *
- *
- * @author caikang
- * @date 2017/06/13
- */
-object InspectionResults {
- private val fileViolations = linkedMapOf>()
-
- var contentDescription = ""
-
- val errors: List
- get() {
- val result = toLevelViolationList(fileViolations.values.flatten())
- contentDescription = getContentDescription(result)
- return result
- }
-
- lateinit var view: InspectionResultView
-
-
- fun clear() {
- fileViolations.forEach {
- MarkerUtil.removeAllMarkers(it.key)
- }
- fileViolations.clear()
- // update contentDescription
- errors
- }
-
- private fun toLevelViolationList(markers: Collection): List {
- return markers.groupBy {
- it.violation.rule.priority.priority
- }.mapValues {
- it.value.groupBy {
- it.violation.rule.name
- }.mapValues {
- it.value.groupBy {
- it.marker.resource as IFile
- }.map {
- FileMarkers(it.key, it.value)
- }
- }.map {
- RuleViolations(it.key, it.value)
- }
- }.toSortedMap().map {
- val level = RulePriority.valueOf(it.key).title
- LevelViolations(level, it.value)
- }
- }
-
- fun updateFileViolations(file: IFile, markers: List) {
- if (markers.isEmpty()) {
- fileViolations.remove(file)
- } else {
- fileViolations[file] = markers
- }
- view.refreshView(this)
- }
-
- fun removeMarker(marker: IMarker) {
- val file = marker.resource as IFile
- val list = fileViolations[file] ?: return
- val result = list.filter {
- it.marker != marker
- }
- fileViolations[file] = result
- marker.delete()
- view.refreshView(this)
- }
-
- fun getContentDescription(errors: List): String {
- val map = errors.associateBy {
- it.level
- }
-
- return "${map[RulePriority.Blocker.title]?.count ?: 0} Blockers," +
- "${map[RulePriority.Critical.title]?.count ?: 0} Criticals," +
- "${map[RulePriority.Major.title]?.count ?: 0} Majors"
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/QuickFixAction.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/QuickFixAction.kt
deleted file mode 100644
index 9dfb33d77..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/QuickFixAction.kt
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.ui
-
-import com.alibaba.p3c.pmd.lang.java.rule.flowcontrol.NeedBraceRule
-import com.alibaba.smartfox.eclipse.RunWithoutViewRefresh
-import com.alibaba.smartfox.eclipse.SmartfoxActivator
-import com.alibaba.smartfox.eclipse.job.CodeAnalysis
-import com.alibaba.smartfox.eclipse.job.P3cMutex
-import com.alibaba.smartfox.eclipse.pmd.rule.MissingOverrideAnnotationRule
-import com.alibaba.smartfox.eclipse.util.CleanUps
-import com.alibaba.smartfox.eclipse.util.getResolution
-import org.eclipse.core.runtime.IProgressMonitor
-import org.eclipse.core.runtime.IStatus
-import org.eclipse.core.runtime.Status
-import org.eclipse.core.runtime.SubMonitor
-import org.eclipse.core.runtime.jobs.Job
-import org.eclipse.jface.action.Action
-
-/**
- *
- *
- * @author caikang
- * @date 2017/06/14
- */
-class QuickFixAction(val view: InspectionResultView) : Action("Quick Fix") {
- init {
- imageDescriptor = SmartfoxActivator.getImageDescriptor("icons/actions/quickfixBulb.png")
- isEnabled = false
- }
-
- var markers = listOf()
-
- fun updateFileMarkers(markers: List) {
- this.markers = markers
- isEnabled = enabled()
- }
-
- override fun run() {
- if (markers.isEmpty()) {
- return
- }
- runJob()
- }
-
- private fun runJob() {
- val job = object : Job("Perform P3C Quick Fix") {
- override fun run(monitor: IProgressMonitor): IStatus {
- val subMonitor = SubMonitor.convert(monitor, markers.size)
- monitor.setTaskName("Process File")
- markers.forEach {
- if (monitor.isCanceled) {
- return@run Status.CANCEL_STATUS
- }
- monitor.subTask(it.file.name)
- val childMonitor = subMonitor.newChild(1)
- if (useCleanUpRefactoring()) {
- CleanUps.fix(it.file, childMonitor)
- } else {
- it.markers.filter { it.marker.exists() }.forEach {
- (it.marker.getResolution() as RunWithoutViewRefresh).run(it.marker, true)
- }
- }
- val markers = CodeAnalysis.processFileToMakers(it.file, monitor)
- InspectionResults.updateFileViolations(it.file, markers)
- }
-
- return Status.OK_STATUS
- }
- }
- val outJob = object:Job("P3C Quick Fix Wait analysis finish"){
- override fun run(monitor: IProgressMonitor?): IStatus {
- job.schedule()
- return Status.OK_STATUS
- }
- }
- outJob.rule = P3cMutex
- outJob.schedule()
-
- }
-
- fun enabled(): Boolean {
- if (useCleanUpRefactoring()) {
- return true
- }
- if (markers.isEmpty()) {
- return false
- }
- val marker = markers.first().markers.first().marker
- return marker.exists() && marker.getResolution() != null
- }
-
- private fun useCleanUpRefactoring(): Boolean {
- if (markers.isEmpty()) {
- return false
- }
- val ruleName = markers.first().markers.first().violation.rule.name
- return ruleName == MissingOverrideAnnotationRule::class.java.simpleName
- || ruleName == NeedBraceRule::class.java.simpleName
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/RuleDetailComposite.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/RuleDetailComposite.kt
deleted file mode 100644
index 667e276ee..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/RuleDetailComposite.kt
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.ui
-
-import com.alibaba.smartfox.eclipse.pmd.RulePriority
-import com.alibaba.smartfox.eclipse.ui.pmd.ContentBuilder
-import com.alibaba.smartfox.eclipse.ui.pmd.StringArranger
-import net.sourceforge.pmd.Rule
-import org.eclipse.swt.SWT
-import org.eclipse.swt.custom.StyledText
-import org.eclipse.swt.layout.FillLayout
-import org.eclipse.swt.widgets.Composite
-
-/**
- *
- * @author caikang
- * @date 2017/09/01
- */
-class RuleDetailComposite(parent: Composite, style: Int = SWT.NONE) {
- private val viewField: StyledText
- private val contentBuilder = ContentBuilder()
- private val arranger = StringArranger(" ")
- private val panel = Composite(parent, style)
-
- init {
- panel.layout = FillLayout()
-
- viewField = StyledText(panel, SWT.BORDER or SWT.H_SCROLL or SWT.V_SCROLL)
- viewField.wordWrap = true
- viewField.tabs = 20
- viewField.text = "Select a result item to show rule detail."
- viewField.editable = false
- }
-
- fun refresh(rule: Rule) {
- contentBuilder.clear()
- viewField.text = ""
- contentBuilder.addHeading("Name")
- contentBuilder.addText(rule.name)
- contentBuilder.addHeading("Severity")
- contentBuilder.addText(RulePriority.valueOf(rule.priority.priority).title)
- contentBuilder.addHeading("Message")
- contentBuilder.addText(rule.message)
- if (!rule.description.isNullOrBlank()) {
- contentBuilder.addHeading("Description")
- contentBuilder.addRawText(arranger.format(rule.description).toString())
- }
-
- val examples = rule.examples
- if (examples.isEmpty()) {
- contentBuilder.showOn(viewField)
- return
- }
-
- contentBuilder.setLanguage(rule.language)
-
- contentBuilder.addHeading("Examples")
- contentBuilder.addText("")
- for (example in rule.examples) {
- contentBuilder.addCode(example.trim { it <= ' ' })
- contentBuilder.addText("")
- }
- contentBuilder.showOn(viewField)
-
- if (contentBuilder.hasLinks()) {
- contentBuilder.addLinkHandler(viewField)
- }
- viewField.update()
- }
-}
\ No newline at end of file
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/RuleDetailView.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/RuleDetailView.kt
deleted file mode 100644
index 915adf798..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/RuleDetailView.kt
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.ui
-
-import com.alibaba.smartfox.eclipse.SmartfoxActivator
-import net.sourceforge.pmd.Rule
-import org.eclipse.jface.action.Action
-import org.eclipse.jface.action.Separator
-import org.eclipse.swt.SWT
-import org.eclipse.swt.custom.ScrolledComposite
-import org.eclipse.swt.layout.FillLayout
-import org.eclipse.swt.widgets.Composite
-import org.eclipse.swt.widgets.Display
-import org.eclipse.swt.widgets.Shell
-import org.eclipse.ui.IWorkbenchPage
-import org.eclipse.ui.PlatformUI
-import org.eclipse.ui.part.ViewPart
-
-
-/**
- *
- *
- * @author caikang
- * @date 2017/06/12
- */
-open class RuleDetailView : ViewPart() {
-
- private lateinit var ruleDetailComposite: RuleDetailComposite
-
- override fun setFocus() {
- }
-
- override fun createPartControl(parent: Composite) {
- ruleDetailComposite = RuleDetailComposite(parent)
- initToolBar()
- }
-
- fun refresh(rule: Rule) {
- ruleDetailComposite.refresh(rule)
- }
-
-
- private fun initToolBar() {
- val bars = viewSite.actionBars
- val tm = bars.toolBarManager
-
- val rulesAction = object : Action("Show Rules") {
- override fun run() {
- val shell = Shell(Display.getDefault())
- shell.text = "All Rules"
- shell.layout = FillLayout()
-
- val sc = ScrolledComposite(shell, SWT.V_SCROLL or SWT.H_SCROLL)
-
- val rulesView = AllRulesView(sc)
-
- sc.expandHorizontal = true
- sc.expandVertical = true
-
- sc.content = rulesView.content
-
- shell.open()
- }
- }
-
- rulesAction.imageDescriptor = SmartfoxActivator.getImageDescriptor("icons/actions/rules.png")
-
- tm.add(Separator("Markers"))
- tm.add(rulesAction)
- }
-
- companion object {
- fun showAndGetView(): RuleDetailView {
- return PlatformUI.getWorkbench().activeWorkbenchWindow.activePage.showView(
- "com.alibaba.smartfox.eclipse.ui.RuleDetailView", null,
- IWorkbenchPage.VIEW_VISIBLE) as RuleDetailView
- }
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/Violations.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/Violations.kt
deleted file mode 100644
index ddb7a098d..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/Violations.kt
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.smartfox.eclipse.ui
-
-import com.alibaba.smartfox.eclipse.util.MarkerUtil
-import net.sourceforge.pmd.RuleViolation
-import org.eclipse.core.resources.IFile
-import org.eclipse.core.resources.IMarker
-
-/**
- *
- *
- * @author caikang
- * @date 2017/06/13
- */
-data class LevelViolations(var level: String, var rules: List,
- var count: Int = rules.sumBy { it.count }) {
- fun removeMarkers() {
- rules.forEach {
- it.removeMarkers()
- }
- }
-
- override fun equals(other: Any?): Boolean {
- if (other !is LevelViolations) {
- return false
- }
- return level == other.level
- }
-
- override fun hashCode(): Int {
- return level.hashCode()
- }
-}
-
-data class RuleViolations(var rule: String, var files: List,
- var count: Int = files.sumBy { it.markers.size }) {
- fun removeMarkers() {
- files.forEach {
- it.removeMarkers()
- }
- }
-
- override fun equals(other: Any?): Boolean {
- if (other !is RuleViolations) {
- return false
- }
- return rule == other.rule
- }
-
- override fun hashCode(): Int {
- return rule.hashCode()
- }
-}
-
-data class FileMarkers(var file: IFile, var markers: List) {
- fun removeMarkers() {
- MarkerUtil.removeAllMarkers(file)
- }
-
- override fun equals(other: Any?): Boolean {
- if (other !is FileMarkers) {
- return false
- }
- return file == other.file
- }
-
- override fun hashCode(): Int {
- return file.hashCode()
- }
-}
-
-data class MarkerViolation(val marker: IMarker, val violation: RuleViolation)
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/BasicLineStyleListener.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/BasicLineStyleListener.kt
deleted file mode 100644
index aff3777b8..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/BasicLineStyleListener.kt
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.alibaba.smartfox.eclipse.ui.pmd
-
-import org.eclipse.swt.custom.LineStyleEvent
-import org.eclipse.swt.custom.LineStyleListener
-
-/**
- * This class performs the syntax highlighting and styling for Pmpe
- * * PmpeLineStyleListener constructor
-
- * @param theSyntaxData the syntax data to use
- */
-class BasicLineStyleListener(theSyntaxData: SyntaxData) : StyleExtractor(theSyntaxData), LineStyleListener {
- /**
- * Called by StyledText to get styles for a line
- */
- override fun lineGetStyle(event: LineStyleEvent) {
- val styles = lineStylesFor(event.lineText, event.lineOffset, event.lineText.length)
- event.styles = styles.toTypedArray()
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/ContentBuilder.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/ContentBuilder.kt
deleted file mode 100644
index 21ca57259..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/ContentBuilder.kt
+++ /dev/null
@@ -1,158 +0,0 @@
-package com.alibaba.smartfox.eclipse.ui.pmd
-
-import net.sourceforge.pmd.lang.Language
-import org.eclipse.swt.SWT
-import org.eclipse.swt.custom.StyleRange
-import org.eclipse.swt.custom.StyledText
-import org.eclipse.swt.graphics.Point
-import org.eclipse.swt.widgets.Display
-import org.eclipse.ui.PlatformUI
-import java.net.URL
-import java.util.ArrayList
-import java.util.Arrays
-import java.util.HashMap
-
-/**
- *
- * @author caikang
- * @date 2017/07/20
- */
-class ContentBuilder {
- private val CR = '\n'
- private val buffer = StringBuilder()
- private val headingSpans = ArrayList()
- private val codeSpans = ArrayList()
- private val linksBySpan = HashMap()
-
- private val indentDepth: Int = 3
-
- private val codeStyleExtractor = StyleExtractor(SyntaxManager.getSyntaxData("java"))
-
- private val background = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)
-
- private val headingColor = Display.getCurrent().getSystemColor(SWT.COLOR_BLUE)
-
- private val codeStyle = FontBuilder("Courier", 11, SWT.NORMAL).style(Display.getCurrent())
-
- fun clear() {
- buffer.setLength(0)
- headingSpans.clear()
- codeSpans.clear()
- linksBySpan.clear()
- }
-
- fun addHeading(heading: String) {
- var length = buffer.length
- if (length > 0) {
- buffer.append(CR)
- length += 1
- }
-
- headingSpans.add(intArrayOf(length, length + heading.length))
- buffer.append(heading).append(CR)
- }
-
- fun addText(text: String) {
- for (i in 0 until indentDepth) {
- buffer.append(' ')
- }
- buffer.append(text).append(CR)
- }
-
- fun addRawText(text: String) {
- buffer.append(text)
- }
-
- fun addCode(code: String) {
- val length = buffer.length
- codeSpans.add(intArrayOf(length, length + code.length))
- buffer.append(code)
- }
-
- fun setLanguage(language: Language) {
- val syntax = SyntaxManager.getSyntaxData(language.terseName)
- codeStyleExtractor.syntax(syntax)
- }
-
- fun hasLinks(): Boolean {
- return linksBySpan.isNotEmpty()
- }
-
- fun addLinkHandler(widget: StyledText) {
-
- widget.addListener(SWT.MouseDown) { event ->
- // It is up to the application to determine when and how a link
- // should be activated.
- // In this snippet links are activated on mouse down when the
- // control key is held down
- // if ((event.stateMask & SWT.MOD1) != 0) {
- try {
- val offset = widget.getOffsetAtLocation(Point(event.x, event.y))
- val link = linkAt(offset)
- if (link != null) {
- launchBrowser(link)
- }
-
- } catch (e: IllegalArgumentException) {
- // no character under event.x, event.y
- }
- }
- }
-
- private fun linkAt(textIndex: Int): String? {
- var span: IntArray
- for ((key, value) in linksBySpan) {
- span = key
- if (span[0] <= textIndex && textIndex <= span[1]) {
- return value
- }
- }
- return null
- }
-
- private fun launchBrowser(link: String) {
- try {
- val browser = PlatformUI.getWorkbench().browserSupport.externalBrowser
- browser.openURL(URL(link))
- } catch (ex: Exception) {
- ex.printStackTrace()
- }
- }
-
- fun showOn(widget: StyledText) {
- val text = buffer.toString()
- widget.text = text
- val ranges = ArrayList()
- var span: IntArray
- for (i in headingSpans.indices) {
- span = headingSpans[i]
- ranges.add(StyleRange(span[0], span[1] - span[0], headingColor, background, SWT.BOLD))
- }
- for (spn in linksBySpan.keys) {
- val style = StyleRange(spn[0], spn[1] - spn[0], headingColor, background, SWT.UNDERLINE_LINK)
- style.underline = true
- ranges.add(style)
- }
- val crStr = Character.toString(CR)
- var sr: StyleRange
-
- for (i in codeSpans.indices) {
- span = codeSpans[i]
- sr = StyleRange(codeStyle)
- sr.start = span[0]
- sr.length = span[1] - span[0]
-
- val colorRanges = codeStyleExtractor.stylesFor(text, sr.start, sr.length, crStr)
- ranges += colorRanges
- }
- // must be in order!
- val styles = sort(ranges)
- widget.styleRanges = styles
- }
-
- private fun sort(ranges: List): Array {
- val styles = ranges.toTypedArray()
- Arrays.sort(styles) { sr1, sr2 -> sr1.start - sr2.start }
- return styles
- }
-}
\ No newline at end of file
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/FontBuilder.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/FontBuilder.kt
deleted file mode 100644
index 75b61359a..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/FontBuilder.kt
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.alibaba.smartfox.eclipse.ui.pmd
-
-import org.eclipse.swt.graphics.Font
-import org.eclipse.swt.graphics.TextStyle
-import org.eclipse.swt.widgets.Display
-
-/**
- * @author Brian Remedios
- */
-class FontBuilder(val name: String, val size: Int, val style: Int, val colorIdx: Int = -1) {
-
- fun build(display: Display): Font {
- return Font(display, name, size, style)
- }
-
- fun style(display: Display): TextStyle {
- return TextStyle(build(display), if (colorIdx < 0) null else display.getSystemColor(colorIdx), null)
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/StringArranger.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/StringArranger.kt
deleted file mode 100644
index 78cd5ae54..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/StringArranger.kt
+++ /dev/null
@@ -1,54 +0,0 @@
-package com.alibaba.smartfox.eclipse.ui.pmd
-
-import net.sourceforge.pmd.util.StringUtil
-import java.util.ArrayList
-
-/**
- * @author Brian Remedios
- */
-class StringArranger(private val indentString: String) {
-
- fun withIndent(rawText: String): String {
- return indentString + rawText
- }
-
- fun format(rawText: String): StringBuilder {
-
- val sb = StringBuilder()
- for (line in trimmedLinesIn(rawText)) {
- sb.append(indentString)
- sb.append(line).append(CR)
- }
-
- return sb
- }
-
- fun trimmedLinesIn(text: String): List {
-
- val lines = text.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
- if (lines.isEmpty()) {
- return emptyList()
- }
-
- val lineSet = ArrayList(lines.size)
-
- var startLine = 0
- while (startLine < lines.size && StringUtil.isEmpty(lines[startLine])) {
- startLine++
- }
-
- var endLine = lines.size - 1
- while (endLine >= 0 && StringUtil.isEmpty(lines[endLine])) {
- endLine--
- }
-
- lines.mapTo(lineSet) {
- it.trim { it <= ' ' }
- }
- return lineSet
- }
-
- companion object {
- private val CR = '\n'
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/StyleExtractor.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/StyleExtractor.kt
deleted file mode 100644
index 07b8821e6..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/StyleExtractor.kt
+++ /dev/null
@@ -1,275 +0,0 @@
-package com.alibaba.smartfox.eclipse.ui.pmd
-
-import net.sourceforge.pmd.util.StringUtil
-import org.eclipse.swt.SWT
-import org.eclipse.swt.custom.StyleRange
-import org.eclipse.swt.widgets.Display
-import java.util.ArrayList
-import java.util.LinkedList
-
-/**
- * @author Brian Remedios
- */
-open class StyleExtractor(private var syntaxData: SyntaxData?) {
- private val commentOffsets: MutableList
-
- init {
- commentOffsets = LinkedList()
- }
-
- fun syntax(theSyntax: SyntaxData?) {
- syntaxData = theSyntax
- }
-
- /**
- * Refreshes the offsets for all multiline comments in the parent
- * StyledText. The parent StyledText should call this whenever its text is
- * modified. Note that this code doesn't ignore comment markers inside
- * strings.
-
- * @param text the text from the StyledText
- */
- fun refreshMultilineComments(text: String) {
- // Clear any stored offsets
- commentOffsets.clear()
-
- if (syntaxData != null) {
- // Go through all the instances of COMMENT_START
- var pos = text.indexOf(syntaxData!!.multiLineCommentStart!!)
- while (pos > -1) {
- // offsets[0] holds the COMMENT_START offset
- // and COMMENT_END holds the ending offset
- val offsets = IntArray(2)
- offsets[0] = pos
-
- // Find the corresponding end comment.
- pos = text.indexOf(syntaxData!!.multiLineCommentEnd!!, pos)
-
- // If no corresponding end comment, use the end of the text
- offsets[1] = if (pos == -1) text.length - 1 else pos + syntaxData!!.multiLineCommentEnd!!.length - 1
- pos = offsets[1]
- // Add the offsets to the collection
- commentOffsets.add(offsets)
- pos = text.indexOf(syntaxData!!.multiLineCommentStart!!, pos)
- }
- }
- }
-
- /**
- * Checks to see if the specified section of text begins inside a multiline
- * comment. Returns the index of the closing comment, or the end of the line
- * if the whole line is inside the comment. Returns -1 if the line doesn't
- * begin inside a comment.
-
- * @param start the starting offset of the text
- * @param length the length of the text
- * @return int
- */
- private fun getBeginsInsideComment(start: Int, length: Int): Int {
- // Assume section doesn't being inside a comment
- var index = -1
-
- // Go through the multiline comment ranges
- var i = 0
- val n = commentOffsets.size
- while (i < n) {
- val offsets = commentOffsets[i]
-
- // If starting offset is past range, quit
- if (offsets[0] > start + length) {
- break
- }
- // Check to see if section begins inside a comment
- if (offsets[0] <= start && offsets[1] >= start) {
- // It does; determine if the closing comment marker is inside
- // this section
- index = if (offsets[1] > start + length) start + length
- else offsets[1] + syntaxData!!.multiLineCommentEnd!!.length - 1
- }
- i++
- }
- return index
- }
-
- private fun isDefinedVariable(text: String): Boolean {
- return StringUtil.isNotEmpty(text)
- }
-
- private fun atMultiLineCommentStart(text: String, position: Int): Boolean {
- return text.indexOf(syntaxData!!.multiLineCommentStart!!, position) == position
- }
-
- private fun atStringStart(text: String, position: Int): Boolean {
- return text.indexOf(syntaxData!!.stringStart!!, position) == position
- }
-
- private fun atVarnameReference(text: String, position: Int): Boolean {
- return syntaxData!!.varnameReference != null && text.indexOf(syntaxData!!.varnameReference!!,
- position) == position
- }
-
- private fun atSingleLineComment(text: String, position: Int): Boolean {
- return syntaxData!!.comment != null && text.indexOf(syntaxData!!.comment!!, position) == position
- }
-
- private fun getKeywordEnd(lineText: String, start: Int): Int {
-
- val length = lineText.length
-
- val buf = StringBuilder(length)
- var i = start
-
- // Call any consecutive letters a word
- while (i < length && Character.isLetter(lineText[i])) {
- buf.append(lineText[i])
- i++
- }
-
- return if (syntaxData!!.isKeyword(buf.toString())) i else 0 - i
- }
-
- /**
- * Chop up the text into individual lines starting from offset and then
- * determine the required styles for each. Ensures the offset is properly
- * accounted for in each.
-
- * @param text
- * @param offset
- * @param length
- * @return
- */
- fun stylesFor(text: String, offset: Int, length: Int, lineSeparator: String): List {
-
- if (syntaxData == null) {
- return emptyList()
- }
-
- val content = text.substring(offset, offset + length)
- val lines = content.split(lineSeparator.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
-
- val styles = ArrayList()
-
- val separatorLength = lineSeparator.length
-
- var currentOffset = offset
-
- for (line in lines) {
- val lineLength = line.length
- val lineStyles = lineStylesFor(line, 0, lineLength)
-
- for (sr in lineStyles) {
- sr.start += currentOffset
- }
- styles.addAll(lineStyles)
- currentOffset += lineLength + separatorLength
- }
-
- return styles
- }
-
- fun lineStylesFor(lineText: String, lineOffset: Int, length: Int): List {
-
- val styles = ArrayList()
-
- var start = 0
-
- // Check if line begins inside a multiline comment
- val mlIndex = getBeginsInsideComment(lineOffset, lineText.length)
- if (mlIndex > -1) {
- // Line begins inside multiline comment; create the range
- styles.add(StyleRange(lineOffset, mlIndex - lineOffset, COMMENT_COLOR, COMMENT_BACKGROUND))
- start = mlIndex
- }
- // Do punctuation, single-line comments, and keywords
- while (start < length) {
- // Check for multiline comments that begin inside this line
- if (atMultiLineCommentStart(lineText, start)) {
- // Determine where comment ends
- var endComment = lineText.indexOf(syntaxData!!.multiLineCommentEnd!!, start)
-
- // If comment doesn't end on this line, extend range to end of
- // line
- if (endComment == -1) {
- endComment = length
- } else {
- endComment += syntaxData!!.multiLineCommentEnd!!.length
- }
- styles.add(StyleRange(lineOffset + start, endComment - start, COMMENT_COLOR, COMMENT_BACKGROUND))
-
- start = endComment
- } else if (atStringStart(lineText, start)) {
- // Determine where comment ends
- var endString = lineText.indexOf(syntaxData!!.stringEnd!!, start + 1)
-
- // If string doesn't end on this line, extend range to end of
- // line
- if (endString == -1) {
- endString = length
- } else {
- endString += syntaxData!!.stringEnd!!.length
- }
- styles.add(StyleRange(lineOffset + start, endString - start, STRING_COLOR, COMMENT_BACKGROUND))
-
- start = endString
- } else if (atSingleLineComment(lineText, start)) {
- // line comments
-
- styles.add(StyleRange(lineOffset + start, length - start, COMMENT_COLOR, COMMENT_BACKGROUND))
- start = length
- } else if (atVarnameReference(lineText, start)) {
- // variable
- // references
-
- val buf = StringBuilder()
- var i = start + syntaxData!!.varnameReference!!.length
- // Call any consecutive letters a word
- while (i < length && Character.isLetter(lineText[i])) {
- buf.append(lineText[i])
- i++
- }
-
- // See if the word is a variable
- if (isDefinedVariable(buf.toString())) {
- // It's a keyword; create the StyleRange
- styles.add(StyleRange(lineOffset + start, i - start, REFERENCED_VAR_COLOR, null, SWT.BOLD))
- }
- // Move the marker to the last char (the one that wasn't a
- // letter)
- // so it can be retested in the next iteration through the loop
- start = i
- } else if (syntaxData!!.isPunctuation(lineText[start])) {
- // Add range for punctuation
- styles.add(StyleRange(lineOffset + start, 1, PUNCTUATION_COLOR, null))
- ++start
- } else if (Character.isLetter(lineText[start])) {
-
- val kwEnd = getKeywordEnd(lineText, start)
- // is a keyword
-
- if (kwEnd > start) {
- styles.add(StyleRange(lineOffset + start, kwEnd - start, KEYWORD_COLOR, null))
- }
-
- // Move the marker to the last char (the one that wasn't a
- // letter)
- // so it can be retested in the next iteration through the loop
- start = Math.abs(kwEnd)
- } else {
- ++start // It's nothing we're interested in; advance the marker
- }// Check for punctuation
- }
-
- return styles
- }
-
- companion object {
-
- private val COMMENT_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN)
- private val REFERENCED_VAR_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN)
- private val UNREFERENCED_VAR_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW)
- private val COMMENT_BACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)
- private val PUNCTUATION_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_BLACK)
- private val KEYWORD_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_MAGENTA)
- private val STRING_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_BLUE)
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/SyntaxData.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/SyntaxData.kt
deleted file mode 100644
index 88e0f9dfd..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/SyntaxData.kt
+++ /dev/null
@@ -1,37 +0,0 @@
-package com.alibaba.smartfox.eclipse.ui.pmd
-
-/**
- * This class contains information for syntax coloring and styling for an
- * extension
- */
-class SyntaxData(val extension: String) {
-
- var varnameReference: String? = null
- var stringStart: String? = null
- var stringEnd: String? = null
- private var keywords: Collection? = null
- private var punctuation: String? = null
- var comment: String? = null
- var multiLineCommentStart: String? = null
- var multiLineCommentEnd: String? = null
-
- fun matches(otherExtension: String): Boolean {
- return extension == otherExtension
- }
-
- fun isKeyword(word: String): Boolean {
- return keywords != null && keywords!!.contains(word)
- }
-
- fun isPunctuation(ch: Char): Boolean {
- return punctuation != null && punctuation!!.indexOf(ch) >= 0
- }
-
- fun setKeywords(keywords: Collection) {
- this.keywords = keywords
- }
-
- fun setPunctuation(thePunctuationChars: String) {
- punctuation = thePunctuationChars
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/SyntaxManager.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/SyntaxManager.kt
deleted file mode 100644
index 570e4bc28..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/pmd/SyntaxManager.kt
+++ /dev/null
@@ -1,94 +0,0 @@
-package com.alibaba.smartfox.eclipse.ui.pmd
-
-import org.eclipse.swt.custom.StyledText
-import org.eclipse.swt.events.ModifyListener
-import java.util.HashSet
-import java.util.Hashtable
-import java.util.MissingResourceException
-import java.util.ResourceBundle
-import java.util.StringTokenizer
-
-/**
- * This class manages the syntax coloring and styling data
- */
-object SyntaxManager {
-
- private val syntaxByExtension = Hashtable()
-
- fun adapt(codeField: StyledText, languageCode: String, oldListener: ModifyListener?): ModifyListener? {
-
- if (oldListener != null) {
- codeField.removeModifyListener(oldListener)
- }
-
- val sd = SyntaxManager.getSyntaxData(languageCode) ?: return null
-
- val blsl = BasicLineStyleListener(sd)
- codeField.addLineStyleListener(blsl)
-
- val ml = ModifyListener {
- blsl.refreshMultilineComments(codeField.text)
- codeField.redraw()
- }
- codeField.addModifyListener(ml)
-
- return ml
- }
-
- /**
- * Gets the syntax data for an extension
- */
- @Synchronized fun getSyntaxData(extension: String): SyntaxData? {
- // Check in cache
- var sd: SyntaxData? = syntaxByExtension[extension]
- if (sd == null) {
- // Not in cache; load it and put in cache
- sd = loadSyntaxData(extension)
- if (sd != null) {
- syntaxByExtension.put(sd.extension, sd)
- }
- }
- return sd
- }
-
- /**
- * Loads the syntax data for an extension
- * @return SyntaxData
- */
- private fun loadSyntaxData(filename: String): SyntaxData? {
- var sd: SyntaxData? = null
- try {
- val rb = ResourceBundle.getBundle("/syntax/$filename")
- sd = SyntaxData(filename)
-
- sd.stringStart = rb.getString("stringstart")
- sd.stringEnd = rb.getString("stringend")
- sd.multiLineCommentStart = rb.getString("multilinecommentstart")
- sd.multiLineCommentEnd = rb.getString("multilinecommentend")
-
- // Load the keywords
- val keywords = HashSet()
- val st = StringTokenizer(rb.getString("keywords"), " ")
- while (st.hasMoreTokens()) {
- keywords.add(st.nextToken())
- }
- sd.setKeywords(keywords)
-
- // Load the punctuation
- sd.setPunctuation(rb.getString("punctuation"))
-
- if (rb.containsKey("comment")) {
- sd.comment = rb.getString("comment")
- }
-
- if (rb.containsKey("varnamedelimiter")) {
- sd.varnameReference = rb.getString("varnamedelimiter")
- }
-
- } catch (e: MissingResourceException) {
- // Ignore
- }
-
- return sd
- }
-}
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/util/CleanUps.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/util/CleanUps.kt
deleted file mode 100644
index a5eba1dd4..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/util/CleanUps.kt
+++ /dev/null
@@ -1,361 +0,0 @@
-// =====================================================================
-//
-// Copyright (C) 2012 - 2016, Philip Graf
-//
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// which accompanies this distribution, and is available at
-// http://www.eclipse.org/legal/epl-v10.html
-//
-// =====================================================================
-package com.alibaba.smartfox.eclipse.util
-
-import com.alibaba.smartfox.eclipse.SmartfoxActivator
-import org.eclipse.core.filebuffers.FileBuffers
-import org.eclipse.core.filebuffers.ITextFileBuffer
-import org.eclipse.core.filebuffers.LocationKind
-import org.eclipse.core.resources.IFile
-import org.eclipse.core.runtime.Assert
-import org.eclipse.core.runtime.CoreException
-import org.eclipse.core.runtime.IProgressMonitor
-import org.eclipse.core.runtime.IStatus
-import org.eclipse.core.runtime.NullProgressMonitor
-import org.eclipse.core.runtime.Status
-import org.eclipse.jdt.core.ICompilationUnit
-import org.eclipse.jdt.core.IJavaProject
-import org.eclipse.jdt.core.JavaCore
-import org.eclipse.jdt.core.dom.CompilationUnit
-import org.eclipse.jdt.internal.corext.fix.CleanUpConstants
-import org.eclipse.jdt.internal.corext.fix.CleanUpRefactoring
-import org.eclipse.jdt.internal.corext.fix.FixMessages
-import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser
-import org.eclipse.jdt.internal.ui.JavaPlugin
-import org.eclipse.jdt.internal.ui.actions.ActionUtil
-import org.eclipse.jdt.internal.ui.fix.MapCleanUpOptions
-import org.eclipse.jdt.ui.SharedASTProvider
-import org.eclipse.jdt.ui.cleanup.CleanUpContext
-import org.eclipse.jdt.ui.cleanup.CleanUpOptions
-import org.eclipse.jdt.ui.cleanup.ICleanUp
-import org.eclipse.jface.text.BadLocationException
-import org.eclipse.jface.text.IDocument
-import org.eclipse.jface.text.IDocumentExtension4
-import org.eclipse.jface.window.Window
-import org.eclipse.ltk.core.refactoring.Change
-import org.eclipse.ltk.core.refactoring.CompositeChange
-import org.eclipse.ltk.core.refactoring.IRefactoringCoreStatusCodes
-import org.eclipse.ltk.core.refactoring.NullChange
-import org.eclipse.ltk.core.refactoring.PerformChangeOperation
-import org.eclipse.ltk.core.refactoring.RefactoringCore
-import org.eclipse.ltk.core.refactoring.RefactoringStatus
-import org.eclipse.ltk.core.refactoring.TextFileChange
-import org.eclipse.ltk.ui.refactoring.RefactoringUI
-import org.eclipse.text.edits.MalformedTreeException
-import org.eclipse.text.edits.TextEdit
-import org.eclipse.text.edits.UndoEdit
-import org.eclipse.ui.PlatformUI
-import java.util.ArrayList
-import java.util.HashMap
-import java.util.LinkedList
-
-/**
- *
- *
- * @author caikang
- * @date 2017/06/15
- */
-object CleanUps {
-
- private val WARNING_VALUE = "warning"
- private val ERROR_VALUE = "error"
-
- val cleanUpSettings = mapOf(CleanUpConstants.ADD_MISSING_ANNOTATIONS to CleanUpOptions.TRUE,
- CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_ALWAYS to CleanUpOptions.TRUE,
- CleanUpConstants.ADD_MISSING_ANNOTATIONS_OVERRIDE to CleanUpOptions.TRUE,
- CleanUpConstants.CONTROL_STATEMENTS_USE_BLOCKS to CleanUpOptions.TRUE,
- CleanUpConstants.ADD_MISSING_ANNOTATIONS_OVERRIDE_FOR_INTERFACE_METHOD_IMPLEMENTATION to
- CleanUpOptions.TRUE)
-
- fun fix(file: IFile, monitor: IProgressMonitor) {
- val compilationUnit = JavaCore.createCompilationUnitFrom(file) ?: return
- doCleanUp(compilationUnit, monitor)
- }
-
- @Throws(CoreException::class) fun doCleanUp(unit: ICompilationUnit, monitor: IProgressMonitor) {
-
- monitor.beginTask("Fix", IProgressMonitor.UNKNOWN)
-
- if (!ActionUtil.isOnBuildPath(unit)) return
- val result = CompositeChange(FixMessages.CleanUpPostSaveListener_SaveAction_ChangeName)
- val undoEdits = LinkedList()
- val oldFileValue = unit.resource.modificationStamp
- val oldDocValue = getDocumentStamp(unit.resource as IFile, monitor)
- val manager = RefactoringCore.getUndoManager()
- var success = false
-
- try {
- manager.aboutToPerformChange(result)
- success = doCleanUp(unit, monitor, result, undoEdits)
- } finally {
- manager.changePerformed(result, success)
- }
-
- if (undoEdits.size > 0) {
- val undoEditArray = undoEdits.toTypedArray()
- val undo = CleanUpSaveUndo(result.name, unit.resource as IFile, undoEditArray, oldDocValue, oldFileValue)
- undo.initializeValidationData(NullProgressMonitor())
- manager.addUndo(result.name, undo)
- }
- }
-
- @Throws(CoreException::class) private fun getDocumentStamp(file: IFile, monitor: IProgressMonitor): Long {
- val manager = FileBuffers.getTextFileBufferManager()
- val path = file.fullPath
-
- monitor.beginTask("", 2)
-
- var buffer: ITextFileBuffer? = null
- try {
- manager.connect(path, LocationKind.IFILE, monitor)
- buffer = manager.getTextFileBuffer(path, LocationKind.IFILE)
- val document = buffer!!.document
-
- if (document is IDocumentExtension4) {
- return document.modificationStamp
- } else {
- return file.modificationStamp
- }
- } finally {
- if (buffer != null) manager.disconnect(path, LocationKind.IFILE, monitor)
- monitor.done()
- }
- }
-
- private fun doCleanUp(unit: ICompilationUnit, monitor: IProgressMonitor, result: CompositeChange,
- undoEdits: LinkedList): Boolean {
- val cleanUps = JavaPlugin.getDefault().cleanUpRegistry.createCleanUps(
- setOf("org.eclipse.jdt.ui.cleanup.java50", "org.eclipse.jdt.ui.cleanup.control_statements"))
- val preCondition = RefactoringStatus()
- val postCondition = RefactoringStatus()
- cleanUps.forEach { cleanUp ->
- cleanUp.setOptions(MapCleanUpOptions(cleanUpSettings))
-
- preCondition.merge(cleanUp.checkPreConditions(unit.javaProject, arrayOf(unit), monitor))
-
- val options = HashMap(cleanUp.requirements.compilerOptions ?: emptyMap())
-
- var ast = CleanUps.createAst(unit, options, monitor)
- if (cleanUp.requirements.requiresAST()) {
- ast = createAst(unit, options, monitor)
- }
-
- val context = CleanUpContext(unit, ast)
-
- val undoneCleanUps = ArrayList()
- val change = CleanUpRefactoring.calculateChange(context, arrayOf(cleanUp), undoneCleanUps, null)
-
- postCondition.merge(cleanUp.checkPostConditions(monitor))
- if (showStatus(postCondition) != Window.OK) {
- return@doCleanUp false
- }
-
- if (change == null) {
- return@forEach
- }
- result.add(change)
-
- change.initializeValidationData(NullProgressMonitor())
-
- val performChangeOperation = PerformChangeOperation(change)
- performChangeOperation.setSchedulingRule(unit.schedulingRule)
- performChangeOperation.run(monitor)
- performChangeOperation.undoChange
- undoEdits.addFirst(change.undoEdit)
- }
-
- return true
- }
-
- private fun showStatus(status: RefactoringStatus): Int {
- if (!status.hasError()) return Window.OK
-
- val shell = PlatformUI.getWorkbench().activeWorkbenchWindow.shell
-
- val dialog = RefactoringUI.createRefactoringStatusDialog(status, shell, "", false)
- return dialog.open()
- }
-
- private fun createAst(unit: ICompilationUnit, cleanUpOptions: Map,
- monitor: IProgressMonitor): CompilationUnit {
- val project = unit.javaProject
- if (compatibleOptions(project, cleanUpOptions)) {
- val ast = SharedASTProvider.getAST(unit, SharedASTProvider.WAIT_NO, monitor)
- if (ast != null) return ast
- }
-
- val parser = CleanUpRefactoring.createCleanUpASTParser()
- parser.setSource(unit)
-
- val compilerOptions = RefactoringASTParser.getCompilerOptions(unit.javaProject)
- compilerOptions.putAll(cleanUpOptions)
- parser.setCompilerOptions(compilerOptions)
-
- return parser.createAST(monitor) as CompilationUnit
- }
-
- private fun compatibleOptions(project: IJavaProject, cleanUpOptions: Map): Boolean {
- if (cleanUpOptions.isEmpty()) {
- return true
- }
-
- val projectOptions = project.getOptions(true)
-
- return !cleanUpOptions.keys.any {
- val projectOption = projectOptions[it]?.toString()
- val cleanUpOption = cleanUpOptions[it]?.toString()
- !strongerEquals(projectOption, cleanUpOption)
- }
- }
-
- private fun strongerEquals(projectOption: String?, cleanUpOption: String?): Boolean {
- if (projectOption == null) return false
-
- if (ERROR_VALUE == cleanUpOption) {
- return ERROR_VALUE == projectOption
- } else if (WARNING_VALUE == cleanUpOption) {
- return ERROR_VALUE == projectOption || WARNING_VALUE == projectOption
- }
-
- return false
- }
-
- private class CleanUpSaveUndo(name: String, private val fFile: IFile, private val fUndos: Array,
- private val fDocumentStamp: Long, private val fFileStamp: Long) : TextFileChange(name,
- fFile) {
-
- init {
- Assert.isNotNull(fUndos)
- }
-
- public override fun needsSaving(): Boolean {
- return true
- }
-
- @Throws(CoreException::class) override fun perform(monitor: IProgressMonitor?): Change {
- val pm = monitor ?: NullProgressMonitor()
- if (isValid(pm).hasFatalError()) return NullChange()
-
- val manager = FileBuffers.getTextFileBufferManager()
- pm.beginTask("", 2)
- var buffer: ITextFileBuffer? = null
-
- try {
- manager.connect(fFile.fullPath, LocationKind.IFILE, pm)
- buffer = manager.getTextFileBuffer(fFile.fullPath, LocationKind.IFILE)
-
- val document = buffer!!.document
- val oldFileValue = fFile.modificationStamp
- val undoEditCollector = LinkedList()
- val oldDocValue = LongArray(1)
- val setContentStampSuccess = booleanArrayOf(false)
-
- if (!buffer.isSynchronizationContextRequested) {
- performEdit(document, oldFileValue, undoEditCollector, oldDocValue, setContentStampSuccess)
-
- } else {
- val fileBufferManager = FileBuffers.getTextFileBufferManager()
-
- class UIRunnable : Runnable {
- var fDone: Boolean = false
- var fException: Exception? = null
-
- override fun run() {
- synchronized(this) {
- try {
- performEdit(document, oldFileValue, undoEditCollector, oldDocValue,
- setContentStampSuccess)
- } catch (e: BadLocationException) {
- fException = e
- } catch (e: MalformedTreeException) {
- fException = e
- } catch (e: CoreException) {
- fException = e
- } finally {
- fDone = true
- (this as Object).notifyAll()
- }
- }
- }
- }
-
- val runnable = UIRunnable()
-
- synchronized(runnable) {
- fileBufferManager.execute(runnable)
- while (!runnable.fDone) {
- try {
- (runnable as Object).wait(500)
- } catch (x: InterruptedException) {
- }
-
- }
- }
-
- if (runnable.fException != null) {
- if (runnable.fException is BadLocationException) {
- throw runnable.fException as BadLocationException
- } else if (runnable.fException is MalformedTreeException) {
- throw runnable.fException as MalformedTreeException
- } else if (runnable.fException is CoreException) {
- throw runnable.fException as CoreException
- }
- }
- }
-
- buffer.commit(pm, false)
- if (!setContentStampSuccess[0]) {
- fFile.revertModificationStamp(fFileStamp)
- }
-
- return CleanUpSaveUndo(name, fFile, undoEditCollector.toTypedArray(), oldDocValue[0], oldFileValue)
- } catch (e: BadLocationException) {
- throw wrapBadLocationException(e)
- } finally {
- if (buffer != null) manager.disconnect(fFile.fullPath, LocationKind.IFILE, pm)
- }
- }
-
- @Throws(MalformedTreeException::class, BadLocationException::class,
- CoreException::class) private fun performEdit(document: IDocument, oldFileValue: Long,
- editCollector: LinkedList,
- oldDocValue: LongArray,
- setContentStampSuccess: BooleanArray) {
- if (document is IDocumentExtension4) {
- oldDocValue[0] = document.modificationStamp
- } else {
- oldDocValue[0] = oldFileValue
- }
-
- // perform the changes
- fUndos.map { it.apply(document, TextEdit.CREATE_UNDO) }.forEach { editCollector.addFirst(it) }
-
- if (document is IDocumentExtension4 && fDocumentStamp != IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP) {
- try {
- document.replace(0, 0, "", fDocumentStamp)
- setContentStampSuccess[0] = true
- } catch (e: BadLocationException) {
- throw wrapBadLocationException(e)
- }
-
- }
- }
- }
-
- private fun wrapBadLocationException(e: BadLocationException): CoreException {
- var message: String? = e.message
- if (message == null) message = "BadLocationException"
- return CoreException(
- Status(IStatus.ERROR, SmartfoxActivator.PLUGIN_ID, IRefactoringCoreStatusCodes.BAD_LOCATION, message,
- e))
- }
-
-}
\ No newline at end of file
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/util/MarkerUtil.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/util/MarkerUtil.kt
deleted file mode 100644
index 4c021bb98..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/util/MarkerUtil.kt
+++ /dev/null
@@ -1,135 +0,0 @@
-// =====================================================================
-//
-// Copyright (C) 2012 - 2016, Philip Graf
-//
-// All rights reserved. This program and the accompanying materials
-// are made available under the terms of the Eclipse Public License v1.0
-// which accompanies this distribution, and is available at
-// http://www.eclipse.org/legal/epl-v10.html
-//
-// =====================================================================
-package com.alibaba.smartfox.eclipse.util
-
-import com.alibaba.smartfox.eclipse.QuickFixGenerator
-import com.alibaba.smartfox.eclipse.SmartfoxActivator
-import com.google.common.io.Files
-import net.sourceforge.pmd.Rule
-import net.sourceforge.pmd.RulePriority
-import net.sourceforge.pmd.RuleViolation
-import org.eclipse.core.resources.IFile
-import org.eclipse.core.resources.IMarker
-import org.eclipse.core.resources.IProject
-import org.eclipse.core.resources.IResource
-import org.eclipse.core.runtime.CoreException
-import org.eclipse.jface.text.BadLocationException
-import org.eclipse.jface.text.Document
-import org.eclipse.ui.IMarkerResolution
-import java.nio.charset.Charset
-
-/**
- * @author caikang
- * @date 2017/06/08
- */
-object MarkerUtil {
-
- private val PMD_TAB_SIZE = 8
-
- private val MARKER_TYPE = "${SmartfoxActivator.PLUGIN_ID}.p3cMarker"
-
- @Throws(CoreException::class)
- fun removeAllMarkers(file: IFile) {
- try {
- if (file.exists()) {
- file.deleteMarkers(MARKER_TYPE, true, IResource.DEPTH_ZERO)
- }
- } catch (e: Exception) {
- SmartfoxActivator.instance.logError(e.message ?: "", e)
- }
- }
-
- @Throws(CoreException::class)
- fun removeAllMarkers(project: IProject) {
- project.deleteMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE)
- }
-
- @Throws(CoreException::class)
- fun addMarker(file: IFile, violation: RuleViolation): IMarker {
- val marker = file.createMarker(MARKER_TYPE)
- marker.setAttribute(IMarker.MESSAGE, violation.description)
- val severity = when (violation.rule.priority) {
- RulePriority.HIGH -> IMarker.SEVERITY_ERROR
- RulePriority.MEDIUM_HIGH -> IMarker.SEVERITY_WARNING
- else -> IMarker.SEVERITY_INFO
- }
- marker.setRule(violation.rule.name)
- marker.setAttribute(IMarker.SEVERITY, severity)
- marker.setAttribute(IMarker.LINE_NUMBER, Math.max(violation.beginLine, 0))
- val range = getAbsoluteRange(file, violation)
- val start = Math.max(range.start, 0)
- marker.setAttribute(IMarker.CHAR_START, start)
- val end = Math.max(range.end, 0)
- marker.setAttribute(IMarker.CHAR_END, end)
- return marker
- }
-
-
- fun getAbsoluteRange(file: IFile, violation: RuleViolation): Range {
- val content = Files.toString(file.rawLocation.toFile(), Charset.forName(file.charset))
- try {
- return calculateAbsoluteRange(content, violation)
- } catch (e: BadLocationException) {
- return Range(0, 0)
- }
- }
-
- @Throws(BadLocationException::class) private fun calculateAbsoluteRange(content: String,
- violation: RuleViolation): Range {
- val document = Document(content)
-
- // violation line and column start at one, the marker's start and end positions at zero
- val start = getAbsolutePosition(content, document.getLineOffset(violation.beginLine - 1), violation.beginColumn)
- val end = getAbsolutePosition(content, document.getLineOffset(violation.endLine - 1), violation.endColumn)
-
- // for some rules PMD creates violations with the end position before the start position
- val range = if (start <= end) {
- Range(start - 1, end)
- } else {
- Range(end - 1, start)
- }
-
- return range
- }
-
- private fun getAbsolutePosition(content: String, lineOffset: Int, pmdCharOffset: Int): Int {
- var pmdCharCounter = 0
- var absoluteOffset = lineOffset
- while (pmdCharCounter < pmdCharOffset) {
- if (absoluteOffset < content.length) {
- val c = content[absoluteOffset]
- if (c == '\t') {
- pmdCharCounter = (pmdCharCounter / PMD_TAB_SIZE + 1) * PMD_TAB_SIZE
- } else {
- pmdCharCounter++
- }
- } else {
- break
- }
- absoluteOffset++
- }
- return absoluteOffset
- }
-}
-
-fun IMarker.setRule(rule: String) {
- this.setAttribute("rule", rule)
-}
-
-fun IMarker.getRule(): Rule {
- return SmartfoxActivator.instance.getRule(this.getAttribute("rule") as String)
-}
-
-fun IMarker.getResolution(): IMarkerResolution? {
- return QuickFixGenerator.quickFixes[getRule().name]
-}
-
-data class Range(val start: Int, val end: Int)
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/messages/P3cBundle.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/messages/P3cBundle.xml
deleted file mode 100644
index 755afb5ba..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/messages/P3cBundle.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
- 阿里编码规约扫描
-
- 切换语言至英文(English)
- 切换语言至中文
- 切换到English成功,是否重启
- 切换到中文成功,是否重启
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/messages/P3cBundle_en.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/messages/P3cBundle_en.xml
deleted file mode 100644
index 091d2a743..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/messages/P3cBundle_en.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
- Alibaba Coding Guidelines Analyze
- Switch language to English
- Switch language to Chinese
-
- Switch language to English success,restart?
- Switch language to Chinese success,restart?
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/rulesets/java/ali-pmd.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/rulesets/java/ali-pmd.xml
deleted file mode 100644
index 3ae5d7360..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/rulesets/java/ali-pmd.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/rulesets/java/ali-ruleOnEclipse.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/rulesets/java/ali-ruleOnEclipse.xml
deleted file mode 100644
index e25eb51ce..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/rulesets/java/ali-ruleOnEclipse.xml
+++ /dev/null
@@ -1,42 +0,0 @@
-
-
-
-
-
- rule.standalone.MissingOverrideAnnotationRule.desc
- 1
-
-
-
-
-
-
- 1
-
-
- rule.standalone.AvoidUseDeprecationRule.desc
- 2
-
-
-
- rule.standalone.MapOrSetKeyShouldOverrideHashCodeEqualsRule.desc
- 2
-
-
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/syntax/java.properties b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/syntax/java.properties
deleted file mode 100644
index f1c6ed499..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/resources/syntax/java.properties
+++ /dev/null
@@ -1,8 +0,0 @@
-# This file contains the syntax data for .java files
-comment=//
-stringstart="
-stringend="
-multilinecommentstart=/*
-multilinecommentend=*/
-punctuation=(){};:?<>=+-*/&|~!%.[]
-keywords=abstract assert boolean break byte case catch char class const continue do double else enum extends false final finally for if implements import int interface native new null package protected public private return static strictfp super switch synchronized this throws true try void volatile while
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/category.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/category.xml
deleted file mode 100644
index 15c89a264..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/category.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
- Alibaba Java Coding Guidelines
-
-
-
-
-
-
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/pom.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/pom.xml
deleted file mode 100644
index 91a5011e1..000000000
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/pom.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
- 4.0.0
-
- com.alibaba.smartfox.eclipse
- smartfox-eclipse
- 2.0.1-SNAPSHOT
-
- com.alibaba.smartfox.eclipse.updatesite
- eclipse-repository
- 2017
-
diff --git a/eclipse-plugin/doc/images/analyze_result.png b/eclipse-plugin/doc/images/analyze_result.png
deleted file mode 100644
index aad166b7b..000000000
Binary files a/eclipse-plugin/doc/images/analyze_result.png and /dev/null differ
diff --git a/eclipse-plugin/doc/images/eclipse_analyze.png b/eclipse-plugin/doc/images/eclipse_analyze.png
deleted file mode 100644
index 92e933c2c..000000000
Binary files a/eclipse-plugin/doc/images/eclipse_analyze.png and /dev/null differ
diff --git a/eclipse-plugin/doc/images/eclipse_switch_language.png b/eclipse-plugin/doc/images/eclipse_switch_language.png
deleted file mode 100644
index e8f21848a..000000000
Binary files a/eclipse-plugin/doc/images/eclipse_switch_language.png and /dev/null differ
diff --git a/eclipse-plugin/doc/images/install.png b/eclipse-plugin/doc/images/install.png
deleted file mode 100644
index 5a60033c8..000000000
Binary files a/eclipse-plugin/doc/images/install.png and /dev/null differ
diff --git a/eclipse-plugin/pom.xml b/eclipse-plugin/pom.xml
deleted file mode 100644
index b93603c17..000000000
--- a/eclipse-plugin/pom.xml
+++ /dev/null
@@ -1,198 +0,0 @@
-
-
- 4.0.0
- com.alibaba.smartfox.eclipse
- smartfox-eclipse
- 2.0.1-SNAPSHOT
- pom
- 2017
-
- 1.0.0
- ${tycho.version}
- http://download.eclipse.org/releases/neon
- UTF-8
- http://download.eclipse.org/tools/ajdt/46/dev/update
- 1.3.30
- juno
-
-
- com.alibaba.smartfox.eclipse.plugin
- com.alibaba.smartfox.eclipse.feature
- com.alibaba.smartfox.eclipse.updatesite
-
-
-
- junit
- junit
- 4.11
- test
-
-
-
-
-
- org.jetbrains.kotlin
- kotlin-stdlib-jdk8
- ${kotlin.version}
- compile
-
-
-
-
-
- juno
- p2
- http://mirrors.ustc.edu.cn/eclipse/releases/juno/
-
-
- sonatype-nexus-snapshots
- Sonatype Nexus Snapshots
- https://oss.sonatype.org/content/repositories/snapshots
-
- false
-
-
- true
-
-
-
-
-
-
- org.eclipse.tycho
- tycho-maven-plugin
- ${tycho.version}
- true
-
-
- org.eclipse.tycho
- target-platform-configuration
-
-
-
- linux
- gtk
- x86
-
-
- linux
- gtk
- x86_64
-
-
- win32
- win32
- x86
-
-
- win32
- win32
- x86_64
-
-
- macosx
- cocoa
- x86_64
-
-
-
-
-
-
-
-
-
- org.eclipse.tycho
- target-platform-configuration
- ${tycho.version}
-
-
- org.eclipse.tycho
- tycho-compiler-plugin
- ${tycho.version}
-
- 1.8
-
-
-
- UTF-8
-
- -err:-forbidden
-
-
-
- org.codehaus.mojo
- aspectj-maven-plugin
- ${aspectj.plugin.version}
-
-
- org.aspectj
- aspectjtools
- ${aspectj.version}
-
-
-
-
- org.eclipse.tycho
- tycho-packaging-plugin
- ${tycho.version}
-
-
- org.eclipse.tycho
- tycho-surefire-plugin
- ${tycho.version}
-
- true
-
-
-
- org.eclipse.tycho
- tycho-source-plugin
- ${tycho.version}
-
- false
-
-
-
- org.eclipse.tycho
- tycho-p2-director-plugin
- ${tycho.version}
-
-
- org.eclipse.tycho
- tycho-p2-repository-plugin
- ${tycho.version}
-
- smartfox-eclipse-plugin
-
-
-
- org.eclipse.tycho.extras
- tycho-source-feature-plugin
- ${tycho-extras.version}
-
-
- org.eclipse.tycho.extras
- tycho-custom-bundle-plugin
- ${tycho-extras.version}
-
-
- org.eclipse.tycho
- tycho-p2-plugin
- ${tycho.version}
-
- warn
- none
-
-
- http://download.eclipse.org/eclipse/updates/4.4
-
-
-
-
-
-
-
-
diff --git a/idea-plugin/.gitignore b/idea-plugin/.gitignore
index b0bfb71a9..4ef3a798f 100644
--- a/idea-plugin/.gitignore
+++ b/idea-plugin/.gitignore
@@ -70,7 +70,6 @@ configuration/**
# sass gitignore#
.sass-cache
-.idea
# tcc_coverage
coverage.ec
@@ -81,7 +80,6 @@ config.client.*
temp/
*.pid
-*.orig
hsf.configuration/
diff --git a/idea-plugin/README.md b/idea-plugin/README.md
index 488e5d617..9a2b10e13 100644
--- a/idea-plugin/README.md
+++ b/idea-plugin/README.md
@@ -1,8 +1,8 @@
# Idea Plugin
---
## Prepare
-- Project JDK: 1.7+
-- Gradle: 3.0+(Require JDK1.8+ for gradle)
+- Project JDK: 11
+- Gradle: 7.3(Require JDK17 for gradle)
## Build
```
@@ -21,7 +21,7 @@ cd p3c-idea
## Use p3c-common as your plugin dependency
```groovy
-compile 'com.alibaba.p3c.idea:p3c-common:1.0.0'
+compile 'com.xenoamess.p3c.idea:p3c-common:2.2.4.0x-SNAPSHOT'
```
## [中文使用手册](README_cn.md)
## Install
@@ -60,6 +60,23 @@ compile 'com.alibaba.p3c.idea:p3c-common:1.0.0'
We use the idea standard Inspection Results to show our violations.

+
+Results are grouped by tags, which include Blocker,Critical,Major,Warning,Weak Warning.
+
+Blocker, Critical and Major will remain sync with alibaba official version, and will not be changed freely, unless especially declared.
+
+When I see some reasonable third party rules in Community I might add them to Warning or Weak Warning.
+
+Usually, if a third party rule can be followed in every situation, then it is tagged Warning.
+
+Otherwise, if it cannot be followed in some special cases, then it will be tagged Weak Warning.
+
+If you want to use pmd-maven-plugin for auto-analyze and assure,
+
+You should set `3` for having same behavior than alibaba official version.
+
+See example/use-case in `p3c-pmd/pom.xml`
+
We can also analyze file which is modified before vcs checkin.
@@ -76,3 +93,281 @@ compile 'com.alibaba.p3c.idea:p3c-common:1.0.0'

+## Configuration mechanism
+### Configuration file path
+
+For p3c-idea-plugin, configuration file should be put at "$your_project_path/p3c_config.x8l".
+
+For p3c-pmd for maven, configuration file should be put at "$the_dir_you_run_mvn/p3c_config.x8l".
+
+Usually this two position be pointed at a same file.
+
+### File format
+
+File format be [x8l](https://github.com/cyanpotion/x8l).
+Yep I write it.
+
+### File analyze
+
+For example at [cyan_potion](https://github.com/cyanpotion/cyan_potionp3c_config.x8l) ,
+we learn about how it works.
+
+Firstly p3c_config.x8l be at "$your_project_path/p3c_config.x8l".
+
+```
+
+
+
+
+ DAOImpl&
+ GLFW&
+ URL&
+ URI&
+ XInput&
+ PosX&
+ PosY&
+ AWT&
+ XY&
+ drawBoxTC&
+ FPS&
+ ID&
+ lastX&
+ lastY&
+ >
+ >
+
+
+ Hbase&
+ HBase&
+ ID&
+ ConcurrentHashMap&
+ GLFW&
+ URL&
+ URI&
+ JXInput&
+ SettingFileParser_
+ >
+ >
+ >
+
+ PackageNamingRule&
+ AbstractClassShouldStartWithAbstractNamingRule&
+ ThreadPoolCreationRule&
+ MethodTooLongRule&
+ >
+
+ Console
+ >
+
+ com.xenoamess.cyan_potion.base.steam
+ >
+
+ EnumConstantsMustHaveCommentRule>
+ EnumConstantsMustHaveCommentRule>
+ EnumConstantsMustHaveCommentRule>
+ EnumConstantsMustHaveCommentRule>
+ EnumConstantsMustHaveCommentRule>
+ EnumConstantsMustHaveCommentRule>
+
+ UndefineMagicConstantRule>
+
+ AvoidUseDeprecationRule>
+
+ AvoidUseDeprecationRule>
+ AvoidUseDeprecationRule>
+ AvoidUseDeprecationRule>
+
+ LowerCamelCaseVariableNamingRule&AvoidUseDeprecationRule>
+
+ ConstantFieldShouldBeUpperCaseRule>
+ >
+>
+```
+
+Root node's name MUST be "com.alibaba.p3c.pmd.config".
+
+Attribute "version=0.0.1" is version of configuration file.
+It is actually not used yet but stongly suggested force it here,
+as for breaking updates.
+
+For this repo, we opened trim for x8l file, means all readed String will be trimed first.
+
+For example,
+
+```
+
+ Console
+ >
+```
+
+see the TextNode
+
+```
+
+ Console
+
+```
+
+It will be trimmed to `Console` before used.
+
+There can be 4 children nodes under node com.alibaba.p3c.pmd.config, as shown below.
+
+### rule_config
+
+Node rule_config contains detailed settings for some rules.
+
+For example, LowerCamelCaseVariableNamingRule's attribute WHITE_LIST.
+
+This attribute need a String List,
+then we read several TextNodes under a ContentNode as a String List.
+
+### rule_blacklist
+
+Node rule_blacklist contains global settings for a repo,
+means ban rules in this repo globally.
+
+For example, if rule_blacklist contains PackageNamingRule,
+then means in this repo we will not detect PackageNamingRule.
+
+Rule class name in rule_blacklist CAN be SimpleName OR CanonicalName.
+
+### class_blacklist
+
+Node class_blacklist contains global settings for a repo,
+means ban classes in this repo globally.
+
+For example, if class_blacklist contains Console,
+then means in this repo we will not detect anything for all classes whose name be Console.
+
+BE ATTENTION, according to PMD interface reason,
+class names in class_blacklist must be SimpleName.
+
+### package_blacklist
+
+Node package_blacklist contains global settings for a repo,
+means ban packages in this repo globally.
+
+For example, if package_blacklist contains `com.xenoamess`,
+then means in this repo we will not detect anything for all classes whose package under `com.xenoamess`.
+
+BE ATTENTION, it will also ban packages under `com.xenoamess`, like `com.xenoamess.cyan_potion`
+
+### rule_class_pair_blacklist
+
+Node rule_class_pair_blacklist contains settings for class/rule pairs,
+means ban some rules in this repo for some classes.
+
+For example, if rule_class_pair_blacklist contains
+`LowerCamelCaseVariableNamingRule&AvoidUseDeprecationRule>`
+,
+then means in this repo we will not detect LowerCamelCaseVariableNamingRule nor AvoidUseDeprecationRule,
+for all classes whose name be GameInputManager.
+
+
+Rule class name in rule_class_pair_blacklist CAN be SimpleName OR CanonicalName.
+
+BE ATTENTION, according to PMD interface reason,
+class names in rule_class_pair_blacklist must be SimpleName.
+
+### For the X8L Haters
+
+If you really hate x8l you can use json configuration files.
+
+```json
+{
+ "com.alibaba.p3c.pmd.config": {
+ "_attributes": {
+ "version": "0.0.1"
+ },
+ "rule_config": {
+ "LowerCamelCaseVariableNamingRule": {
+ "WHITE_LIST": [
+ "DAOImpl",
+ "GLFW",
+ "URL",
+ "URI",
+ "XInput",
+ "PosX",
+ "PosY",
+ "AWT",
+ "XY",
+ "drawBoxTC",
+ "FPS",
+ "ID",
+ "lastX",
+ "lastY"
+ ]
+ },
+ "ClassNamingShouldBeCamelRule": {
+ "CLASS_NAMING_WHITE_LIST": [
+ "Hbase",
+ "HBase",
+ "ID",
+ "ConcurrentHashMap",
+ "GLFW",
+ "URL",
+ "URI",
+ "JXInput",
+ "SettingFileParser_"
+ ]
+ }
+ },
+ "rule_blacklist": [
+ "PackageNamingRule",
+ "AbstractClassShouldStartWithAbstractNamingRule",
+ "ThreadPoolCreationRule",
+ "MethodTooLongRule"
+ ],
+ "class_blacklist": [
+ "Console"
+ ],
+ "package_blacklist": [
+ "com.xenoamess.cyan_potion.base.steam"
+ ],
+ "rule_class_pair_blacklist": {
+ "JamepadGamepadKeyEnum": [
+ "EnumConstantsMustHaveCommentRule"
+ ],
+ "JXInputGamepadKeyEnum": [
+ "EnumConstantsMustHaveCommentRule"
+ ],
+ "KeyActionEnum": [
+ "EnumConstantsMustHaveCommentRule"
+ ],
+ "KeyboardKeyEnum": [
+ "EnumConstantsMustHaveCommentRule"
+ ],
+ "CodePluginPosition": [
+ "EnumConstantsMustHaveCommentRule"
+ ],
+ "ShapeRelation": [
+ "EnumConstantsMustHaveCommentRule"
+ ],
+ "WaveData": [
+ "UndefineMagicConstantRule"
+ ],
+ "FileUtils": [
+ "AvoidUseDeprecationRule"
+ ],
+ "Font": [
+ "AvoidUseDeprecationRule"
+ ],
+ "Keymap": [
+ "AvoidUseDeprecationRule"
+ ],
+ "WorldForDemo": [
+ "AvoidUseDeprecationRule"
+ ],
+ "GameInputManager": [
+ "LowerCamelCaseVariableNamingRule",
+ "AvoidUseDeprecationRule"
+ ],
+ "Colors": [
+ "ConstantFieldShouldBeUpperCaseRule"
+ ]
+ }
+ }
+}
+```
+
+name it p3c_config.json
diff --git a/idea-plugin/README_cn.md b/idea-plugin/README_cn.md
index 90ab1feb9..6700506cc 100644
--- a/idea-plugin/README_cn.md
+++ b/idea-plugin/README_cn.md
@@ -4,11 +4,11 @@
### 通过Jetbrains官方仓库安装
1. 打开 Settings >> Plugins >> Browse repositories...
- 
+
2. 在搜索框输入alibaba即可看到Alibaba Java Code Guidelines插件,点击Install进行安装,然后重启IDE生效 `注意:因为插件zip包托管在Jetbrains官方CDN上,所以是从国外的服务器进行下载,可能会出现超时的情况`
- 
+
### 通过下载安装包进行安装
1. 打开[插件](https://plugins.jetbrains.com/plugin/10046-alibaba-java-coding-guidelines)页面
@@ -17,7 +17,7 @@
2. Settings >> Plugins >> Install plugin from disk...,选择刚刚下载的zip包安装,然后重启IDE
- 
+
### 注意
@@ -30,11 +30,11 @@
1. 修改字体——Appearance&Behavior -> Appearance -> UI Options -> Name 里面设置成中文字体——如微软雅黑(microsoft yahei light)、文泉驿(linux)
- 
+
2. Switch Language to English and restart.
- 
+
## 插件使用
@@ -49,24 +49,25 @@
检测结果高亮提示,并且鼠标放上去会弹出提示信息。
- 
+
- 
+
#### Intention QuickFix功能
Alt+Enter键可呼出Intention菜单,不同的规则会提示不同信息的Quick Fix按钮
- 
+
#### 关闭实时检测
在某些情况下,我们不希望对代码提示违规信息,比如我们在阅读Github开源项目代码的时候,如果界面出现一堆红色、黄色的提示,此时心里肯定是飘过一万只草泥马。这个时候我们可以通过Inspection的设置关闭实时检测功能。
1. 通过右键快速关闭(打开)所有规则的实时检测功能
- 
+
+
2. 通过Settings >> Editor >> Inspections 进行手动设置
- 
+
也可以关闭某条规则的实时检测功能或者修改提示级别。
@@ -77,43 +78,319 @@ Alt+Enter键可呼出Intention菜单,不同的规则会提示不同信息的Qu
#### 触发扫描
在当前编辑的文件中点击右键,可以在弹出的菜单中触发对该文件的检测。
- 
+
在左侧的Project目录树种点击右键,可以触发对整个工程或者选择的某个目录、文件进行检测。
- 
+
如果您打开了IDE的Toolbar,也可以通过Toolbar中的按钮来触发检测,目前Toolbar的按钮触发的检测范围与您IDE当时的焦点有关,如当前编辑的文件或者是Project目录树选中的项,是不是感觉与右键菜单的检测范围类似呢。
- 
+
使用快捷键(Ctrl+Shift+Alt+J)触发弹出窗口,选择检测范围;您也可自定义快捷键。
- 
+
- 
+
#### 扫描结果
-检测结果直接使用IDEA Run Inspection By Name功能的结果界面,插件的检测结果分级为Blocker、Critical、Major。默认按等级分组,方便统计每个级别错误的数量。
+检测结果直接使用IDEA Run Inspection By Name功能的结果界面,插件的检测结果分级为Blocker、Critical、Major、Warning、Weak Warning。默认按等级分组,方便统计每个级别错误的数量。

-
+其中,Blocker、Critical、Major三个级别保持与阿里巴巴官方版相同,不会轻易改变。如果未来需要改变,则必须在此Readme中注明。
+
+看见有人做了比较有道理的第三方规则的话,会是视情况加入Warning或者Weak Warning。
+
+如无例外,一个第三方规则如果在任何情况下都能够执行,即程序员完全可以实现不违背该规则实现任何功能,则这个规则会被放入Warning。
+
+与之相对的,如果存在特定的条件,使得若需要满足特定条件则必须违背该规则,即程序员存在必须违背该规则的场景,则这个规则会被放入Weak Warning。
+
+如果要使用pmd maven plugin对代码进行自动检查以确保不违反阿里巴巴Java开发手册,
+
+则请设置`3`,以保证与官方版本规则吻合。
+
+使用例可见`p3c-pmd/pom.xml`
+
默认情况我们在结果面板需要双击具体违规项才能打开对应的源文件,开启Autoscroll To Source选项,单击面板中的文件名、或者是具体的违规项的时候IDEA会自动打开对应的源文件。
- 
+
#### QuickFix
对于实现Quick Fix的规则,在结果面板中可以直接一键修复 `注意:IDEA14、15可以通过左下角的灯泡进行一键修复操作。`
- 
+
- 
+
#### 其他
面板中其他按钮的功能大家自行探索吧,就不一一赘述了
### 代码提交时检测
1. 在提交代码框勾选Alibaba Code Guidelines选项
- 
+
2. 如果有违反手册的地方会提示是否继续提交,选择取消后会自动对修改的代码进行扫描
- 
+
+
+## 设置文件机制
+### 文件目录
+对于p3c idea插件来说,配置文件存放的位置为项目根目录下的p3c_config.x8l文件。
+
+对于maven项目来说,配置文件存放的位置为运行mvn的目录下的p3c_config.x8l文件。
+
+经常的,这两个位置指向同一个位置。
+
+### 文件格式
+文件格式为 [x8l](https://github.com/cyanpotion/x8l).
+
+### 文件描述
+
+举个例子,以 [cyan_potion](https://github.com/cyanpotion/cyan_potionp3c_config.x8l) 为例,
+我们来看如何配置p3c_config.x8l
+
+首先,p3c_config.x8l位于项目根目录。
+
+```
+
+
+
+
+ DAOImpl&
+ GLFW&
+ URL&
+ URI&
+ XInput&
+ PosX&
+ PosY&
+ AWT&
+ XY&
+ drawBoxTC&
+ FPS&
+ ID&
+ lastX&
+ lastY&
+ >
+ >
+
+
+ Hbase&
+ HBase&
+ ID&
+ ConcurrentHashMap&
+ GLFW&
+ URL&
+ URI&
+ JXInput&
+ SettingFileParser_
+ >
+ >
+ >
+
+ PackageNamingRule&
+ AbstractClassShouldStartWithAbstractNamingRule&
+ ThreadPoolCreationRule&
+ MethodTooLongRule&
+ >
+
+ Console
+ >
+
+ com.xenoamess.cyan_potion.base.steam
+ >
+
+ EnumConstantsMustHaveCommentRule>
+ EnumConstantsMustHaveCommentRule>
+ EnumConstantsMustHaveCommentRule>
+ EnumConstantsMustHaveCommentRule>
+ EnumConstantsMustHaveCommentRule>
+ EnumConstantsMustHaveCommentRule>
+
+ UndefineMagicConstantRule>
+
+ AvoidUseDeprecationRule>
+
+ AvoidUseDeprecationRule>
+ AvoidUseDeprecationRule>
+ AvoidUseDeprecationRule>
+
+ LowerCamelCaseVariableNamingRule&AvoidUseDeprecationRule>
+
+ ConstantFieldShouldBeUpperCaseRule>
+ >
+>
+```
+
+其中,根节点名必为com.alibaba.p3c.pmd.config 。
+
+属性version=0.0.1为配置文件version,目前尚未实际应用,但是建议写明,以防后续破坏性更新。
+
+对于这个项目,方便/美观起见,我们开启了trim,所有读取的String会被trim,然后再进行处理。
+
+例如,
+
+```
+
+ Console
+ >
+```
+
+中的TextNode
+
+```
+
+ Console
+
+```
+
+会被trim为`Console`然后使用。
+
+com.alibaba.p3c.pmd.config节点下有四个子节点,以下依次讲解。
+
+### rule_config
+
+rule_config节点主要包括对于提供了设置属性的规则的具体设置。
+
+如,LowerCamelCaseVariableNamingRule的WHITE_LIST属性。
+
+该属性要求提供一字符串List,则本项目中读取一个ContentNode下多个TextNode转换为字符串List。
+
+### rule_blacklist
+
+rule_blacklist节点主要包括对该项目的所有类禁用某一规则。
+
+如,rule_blacklist中含有PackageNamingRule,则表明该项目中,检测器不会检测PackageNamingRule。
+
+rule_blacklist中的Rule类名既可以是SimpleName,也可以是CanonicalName。
+
+### class_blacklist
+
+class_blacklist节点主要包括对该项目中的某一类禁用所有规则。
+
+如,class_blacklist中含有Console类,则该项目中所有名为Console的类均不会进行任何检测。
+
+注意,由于PMD技术原因,class_blacklist中的类必须为SimpleName
+
+### package_blacklist
+
+package_blacklist节点主要包括对该项目中的某一个父包禁用所有规则。
+
+如,package_blacklist中含有`com.xenoamess`包,则该项目中所有`com.xenoamess`包下的类均不会进行任何检测。
+
+注意,形如`com.xenoamess.cyan_potion`的,`com.xenoamess`包的子包也会被禁用所有规则。
+
+### rule_class_pair_blacklist
+
+rule_class_pair_blacklist节点主要包括对该项目中的某一类禁用某数个规则。
+
+如,rule_class_pair_blacklist中含有
+
+`LowerCamelCaseVariableNamingRule&AvoidUseDeprecationRule>`
+
+,
+则该项目中所有名为GameInputManager的类中,LowerCamelCaseVariableNamingRule与AvoidUseDeprecationRule不会被检测。
+
+Rule类名既可以是SimpleName,也可以是CanonicalName。
+注意,由于PMD技术原因,被忽略检测的类名必须为SimpleName。
+
+### 为了反X8L主义者干杯
+
+如果你确实讨厌X8L文件格式,你可以使用等价json格式配置文件。
+
+```json
+{
+ "com.alibaba.p3c.pmd.config": {
+ "_attributes": {
+ "version": "0.0.1"
+ },
+ "rule_config": {
+ "LowerCamelCaseVariableNamingRule": {
+ "WHITE_LIST": [
+ "DAOImpl",
+ "GLFW",
+ "URL",
+ "URI",
+ "XInput",
+ "PosX",
+ "PosY",
+ "AWT",
+ "XY",
+ "drawBoxTC",
+ "FPS",
+ "ID",
+ "lastX",
+ "lastY"
+ ]
+ },
+ "ClassNamingShouldBeCamelRule": {
+ "CLASS_NAMING_WHITE_LIST": [
+ "Hbase",
+ "HBase",
+ "ID",
+ "ConcurrentHashMap",
+ "GLFW",
+ "URL",
+ "URI",
+ "JXInput",
+ "SettingFileParser_"
+ ]
+ }
+ },
+ "rule_blacklist": [
+ "PackageNamingRule",
+ "AbstractClassShouldStartWithAbstractNamingRule",
+ "ThreadPoolCreationRule",
+ "MethodTooLongRule"
+ ],
+ "class_blacklist": [
+ "Console"
+ ],
+ "package_blacklist": [
+ "com.xenoamess.cyan_potion.base.steam"
+ ],
+ "rule_class_pair_blacklist": {
+ "JamepadGamepadKeyEnum": [
+ "EnumConstantsMustHaveCommentRule"
+ ],
+ "JXInputGamepadKeyEnum": [
+ "EnumConstantsMustHaveCommentRule"
+ ],
+ "KeyActionEnum": [
+ "EnumConstantsMustHaveCommentRule"
+ ],
+ "KeyboardKeyEnum": [
+ "EnumConstantsMustHaveCommentRule"
+ ],
+ "CodePluginPosition": [
+ "EnumConstantsMustHaveCommentRule"
+ ],
+ "ShapeRelation": [
+ "EnumConstantsMustHaveCommentRule"
+ ],
+ "WaveData": [
+ "UndefineMagicConstantRule"
+ ],
+ "FileUtils": [
+ "AvoidUseDeprecationRule"
+ ],
+ "Font": [
+ "AvoidUseDeprecationRule"
+ ],
+ "Keymap": [
+ "AvoidUseDeprecationRule"
+ ],
+ "WorldForDemo": [
+ "AvoidUseDeprecationRule"
+ ],
+ "GameInputManager": [
+ "LowerCamelCaseVariableNamingRule",
+ "AvoidUseDeprecationRule"
+ ],
+ "Colors": [
+ "ConstantFieldShouldBeUpperCaseRule"
+ ]
+ }
+ }
+}
+```
+
+文件名为p3c_config.json即可。
diff --git a/idea-plugin/build.gradle b/idea-plugin/build.gradle
index 64aa3dbb7..48b43b88b 100644
--- a/idea-plugin/build.gradle
+++ b/idea-plugin/build.gradle
@@ -1,38 +1,64 @@
+static boolean shouldIncludeJava(String idea_version_string) {
+ if (idea_version_string.contains('-')) {
+ idea_version_string = idea_version_string.substring(idea_version_string.indexOf('-') + 1)
+ }
+ if (idea_version_string.contains('.')) {
+ idea_version_string = idea_version_string.substring(0, idea_version_string.indexOf('.'))
+ }
+ try {
+ int idea_version_int = Integer.parseInt(idea_version_string);
+ return idea_version_int >= 2019 || (idea_version_int < 1500 && idea_version_int >= 193);
+ } catch (Exception e) {
+ return true
+ }
+}
+
buildscript {
+ project.ext {
+ kotlin_version = "2.2.21"
+ }
repositories {
+ mavenCentral()
+ mavenLocal()
maven {
url "https://oss.sonatype.org/content/repositories/snapshots/"
}
maven {
- url 'http://dl.bintray.com/jetbrains/intellij-plugin-service'
+ url "https://plugins.gradle.org/m2/"
}
- mavenCentral()
-
+ gradlePluginPortal()
+ google()
}
dependencies {
- classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$project.kotlin_version"
}
}
allprojects {
- group 'com.alibaba.p3c.idea'
+ group 'com.xenoamess.p3c.idea'
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'maven-publish'
-
- sourceCompatibility = 1.8
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
compileJava.options.encoding = 'UTF-8'
+ kotlin {
+ jvmToolchain(17)
+ }
configurations.all {
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}
repositories {
- jcenter()
mavenCentral()
- }
-
- dependencies {
- compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
- testCompile group: 'junit', name: 'junit', version: '4.11'
+ mavenLocal()
+ maven {
+ url "https://oss.sonatype.org/content/repositories/snapshots/"
+ }
+ maven {
+ url "https://plugins.gradle.org/m2/"
+ }
+ gradlePluginPortal()
+ google()
}
}
diff --git a/idea-plugin/gradle.properties b/idea-plugin/gradle.properties
index 637c314fa..b65de0735 100644
--- a/idea-plugin/gradle.properties
+++ b/idea-plugin/gradle.properties
@@ -1,7 +1,12 @@
-kotlin_version=1.3.72
-idea_version=2018.3
+# See https://github.com/JetBrains/gradle-intellij-plugin/
+# See https://www.jetbrains.org/intellij/sdk/docs/reference_guide/intellij_artifacts.html
+# See https://www.jetbrains.com/intellij-repository/releases/
+# See https://www.jetbrains.com/intellij-repository/snapshots/
+#idea_version=2022.1
+idea_version=2024.1
+#idea_version=181.5540.23
+#idea_version=145.258.11
plugin_name=Alibaba Java Coding Guidelines
-gradle_jetbrains_version=0.4.5
systemProp.file.encoding=UTF-8
-
-plugin_version=2.1.0
+plugin_version=2.2.4.0x-SNAPSHOT
+org.gradle.jvmargs='-Dfile.encoding=UTF-8'
diff --git a/idea-plugin/gradle/wrapper/gradle-wrapper.jar b/idea-plugin/gradle/wrapper/gradle-wrapper.jar
index 62d4c0535..f3d88b1c2 100644
Binary files a/idea-plugin/gradle/wrapper/gradle-wrapper.jar and b/idea-plugin/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/idea-plugin/gradle/wrapper/gradle-wrapper.properties b/idea-plugin/gradle/wrapper/gradle-wrapper.properties
index 6c9a22477..067e85613 100644
--- a/idea-plugin/gradle/wrapper/gradle-wrapper.properties
+++ b/idea-plugin/gradle/wrapper/gradle-wrapper.properties
@@ -1,5 +1,6 @@
+#Sat Sep 21 06:16:57 CST 2024
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-6.6-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
diff --git a/idea-plugin/gradlew b/idea-plugin/gradlew
old mode 100755
new mode 100644
diff --git a/idea-plugin/p3c-common/build.gradle b/idea-plugin/p3c-common/build.gradle
index 69ff629e6..31bd4a597 100644
--- a/idea-plugin/p3c-common/build.gradle
+++ b/idea-plugin/p3c-common/build.gradle
@@ -1,9 +1,14 @@
plugins {
- id "org.jetbrains.intellij" version '0.4.5'
+ id 'java'
+ id "org.jetbrains.intellij" version "1.17.4"
+
+ id "org.sonarqube" version "6.3.1.5724"
+
+ id "com.github.ben-manes.versions" version "0.53.0"
}
+
apply plugin: 'kotlin'
apply plugin: 'idea'
-apply plugin: 'maven'
apply plugin: 'signing'
javadoc {
@@ -11,12 +16,14 @@ javadoc {
}
task javadocJar(type: Jar, dependsOn: javadoc) {
- classifier = 'javadoc'
+ archiveClassifier.convention('javadoc');
+ archiveClassifier.set('javadoc');
from 'build/docs/javadoc'
}
task sourcesJar(type: Jar) {
- classifier = 'sources'
+ archiveClassifier.convention('sources');
+ archiveClassifier.set('sources');
from sourceSets.main.allSource
}
@@ -27,76 +34,40 @@ artifacts {
}
def myPlugins = []
-def versionDotIndex = idea_version.indexOf('.')
-def intVersion = versionDotIndex == -1 ? Integer.parseInt(idea_version) : Integer.parseInt(idea_version.substring(0, versionDotIndex))
-if (intVersion >= 2019 || (intVersion < 1000 && intVersion >= 193)) {
- myPlugins = ['java']
+if (shouldIncludeJava(idea_version)) {
+ myPlugins.add('java')
+}
+
+sonarqube {
+ properties {
+ property "sonar.projectKey", "p3c-idea"
+ property "sonar.organization", "xenoamess-github"
+ property "sonar.host.url", "https://sonarcloud.io"
+ property "sonar.login", "023904832cfec46a1aa61bb7aeee156b066cb3bc"
+ }
}
intellij {
- version idea_version
- plugins = myPlugins
- pluginName plugin_name
- updateSinceUntilBuild false
- sandboxDirectory "$project.buildDir/idea-sandbox/$idea_version"
+ version.set(idea_version)
+ plugins.set(myPlugins)
+ pluginName.set(plugin_name)
+ updateSinceUntilBuild.set(false)
+ sandboxDir.set("$project.buildDir/idea-sandbox/$idea_version")
}
-version '2.0.1'
+version plugin_version
ext.isReleaseVersion = !version.endsWith("SNAPSHOT")
dependencies {
- compile group: 'org.freemarker', name: 'freemarker', version: '2.3.25-incubating'
- compile 'com.alibaba.p3c:p3c-pmd:2.1.0'
- compile group: 'org.javassist', name: 'javassist', version: '3.21.0-GA'
-}
-
-uploadArchives {
- repositories {
- mavenDeployer {
- beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
-
- repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
- authentication(userName: findProperty('ossrhUsername'), password: findProperty('ossrhPassword'))
- }
-
- snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") {
- authentication(userName: findProperty('ossrhUsername'), password: findProperty('ossrhPassword'))
- }
-
- pom.project {
- name 'p3c-common'
- packaging 'jar'
- description 'P3c Idea Plugin Common.'
- url 'https://github.com/alibaba/p3c'
-
- scm {
- url 'https://github.com/alibaba/p3c'
- connection 'scm:git:https://git@github.com/alibaba/p3c.git'
- }
-
- licenses {
- license {
- name 'The Apache Software License, Version 2.0'
- url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
- distribution 'repo'
- }
- }
-
- developers {
- developer {
- id 'junlie'
- name 'Junlie'
- email 'sean.caikang@gmail.com'
- }
- developer {
- id 'ZengHou'
- name 'ZengHou'
- email 'fengwei1983@gmail.com'
- }
- }
- }
- }
+ implementation group: 'org.freemarker', name: 'freemarker', version: '2.3.33'
+ implementation("com.xenoamess.p3c:p3c-pmd:$plugin_version") {
+ exclude group: 'org.apache.logging.log4j'
+ exclude group: 'org.slf4j'
}
+ implementation group: 'org.javassist', name: 'javassist', version: '3.30.2-GA'
+ implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$project.kotlin_version"
+ implementation "org.jetbrains.kotlin:kotlin-reflect:$project.kotlin_version"
+ testImplementation group: 'junit', name: 'junit', version: '4.13.2'
}
signing {
diff --git a/idea-plugin/p3c-common/src/main/java/icons/P3cIcons.java b/idea-plugin/p3c-common/src/main/java/icons/P3cIcons.java
index a4908c677..03b94b498 100644
--- a/idea-plugin/p3c-common/src/main/java/icons/P3cIcons.java
+++ b/idea-plugin/p3c-common/src/main/java/icons/P3cIcons.java
@@ -26,13 +26,20 @@
public final class P3cIcons {
private P3cIcons() {
throw new AssertionError("icons.P3cIcons"
- + " instances for you!");
+ + " instances for you!");
}
- public static final Icon ANALYSIS_ACTION = IconLoader.getIcon("/icons/ali-ide-run.png");
+ public static final Icon ANALYSIS_ACTION = IconLoader.getIcon("/icons/ali-ide-run.png", P3cIcons.class);
- public static final Icon PROJECT_INSPECTION_ON = IconLoader.getIcon("/icons/qiyong.png");
- public static final Icon PROJECT_INSPECTION_OFF = IconLoader.getIcon("/icons/tingyong.png");
- public static final Icon LANGUAGE = IconLoader.getIcon("/icons/language.png");
- public static final Icon ALIBABA = IconLoader.getIcon("/icons/alibaba.png");
+ /**
+ * qiyong means 启用
+ */
+ public static final Icon PROJECT_INSPECTION_ON = IconLoader.getIcon("/icons/qiyong.png", P3cIcons.class);
+
+ /**
+ * tingyong means 停用
+ */
+ public static final Icon PROJECT_INSPECTION_OFF = IconLoader.getIcon("/icons/tingyong.png", P3cIcons.class);
+ public static final Icon LANGUAGE = IconLoader.getIcon("/icons/language.png", P3cIcons.class);
+ public static final Icon ALIBABA = IconLoader.getIcon("/icons/alibaba.png", P3cIcons.class);
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/AliInspectionAction.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/AliInspectionAction.kt
index a43af5b8a..d1a884eb9 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/AliInspectionAction.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/AliInspectionAction.kt
@@ -24,23 +24,19 @@ import com.google.common.collect.Lists
import com.intellij.analysis.AnalysisScope
import com.intellij.analysis.AnalysisUIOptions
import com.intellij.analysis.BaseAnalysisActionDialog
+import com.intellij.analysis.problemsView.toolWindow.ProblemsView
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.InspectionsBundle
import com.intellij.codeInspection.ex.GlobalInspectionContextImpl
import com.intellij.codeInspection.ex.InspectionManagerEx
import com.intellij.codeInspection.ex.InspectionToolWrapper
-import com.intellij.openapi.actionSystem.AnAction
-import com.intellij.openapi.actionSystem.AnActionEvent
-import com.intellij.openapi.actionSystem.CommonDataKeys
-import com.intellij.openapi.components.ServiceManager
+import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
-import com.intellij.openapi.wm.ToolWindowId
-import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileSystemItem
@@ -55,7 +51,7 @@ class AliInspectionAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
- val analysisUIOptions = ServiceManager.getService(project, AnalysisUIOptions::class.java)!!
+ val analysisUIOptions = project.getService(AnalysisUIOptions::class.java)!!
analysisUIOptions.GROUP_BY_SEVERITY = true
val managerEx = InspectionManager.getInstance(project) as InspectionManagerEx
@@ -114,9 +110,13 @@ class AliInspectionAction : AnAction() {
}
private fun inspectForKeyEvent(
- project: Project, managerEx: InspectionManagerEx,
- toolWrappers: List>, psiElement: PsiElement?, psiFile: PsiFile?,
- virtualFile: VirtualFile?, analysisScope: AnalysisScope
+ project: Project,
+ managerEx: InspectionManagerEx,
+ toolWrappers: List>,
+ psiElement: PsiElement?,
+ psiFile: PsiFile?,
+ virtualFile: VirtualFile?,
+ analysisScope: AnalysisScope
) {
var module: Module? = null
if (virtualFile != null && project.baseDir != virtualFile) {
@@ -126,14 +126,23 @@ class AliInspectionAction : AnAction() {
val uiOptions = AnalysisUIOptions.getInstance(project)
uiOptions.ANALYZE_TEST_SOURCES = false
val dialog = BaseAnalysisActionDialog(
- "Select Analyze Scope", "Analyze Scope", project, analysisScope,
- module?.name, true, uiOptions, psiElement
+ "Select Analyze Scope",
+ "Analyze Scope",
+ project,
+ BaseAnalysisActionDialog.standardItems(
+ project,
+ analysisScope,
+ module,
+ psiElement
+ ),
+ uiOptions,
+ true
)
if (!dialog.showAndGet()) {
return
}
- val scope = dialog.getScope(uiOptions, analysisScope, project, module)
+ val scope = dialog.getScope(analysisScope)
scope.setSearchInLibraries(true)
val element = psiFile ?: psiElement
createContext(
@@ -163,11 +172,11 @@ class AliInspectionAction : AnAction() {
}
fun createContext(
- toolWrapperList: List>,
- managerEx: InspectionManagerEx, psiElement: PsiElement?,
- projectScopeSelected: Boolean, scope: AnalysisScope
+ toolWrapperList: List>,
+ managerEx: InspectionManagerEx, psiElement: PsiElement?,
+ projectScopeSelected: Boolean, scope: AnalysisScope
):
- GlobalInspectionContextImpl {
+ GlobalInspectionContextImpl {
// remove last same scope content
val project = managerEx.project
val title = getTitle(psiElement, projectScopeSelected)
@@ -177,12 +186,11 @@ class AliInspectionAction : AnAction() {
}
val inspectionContext = createNewGlobalContext(
- managerEx, projectScopeSelected
+ managerEx, projectScopeSelected
)
InspectionProfileService.setExternalProfile(model, inspectionContext)
- val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.INSPECTION)
-
+ val toolWindow = ProblemsView.getToolWindow(project);
if (toolWindow != null) {
val contentManager = toolWindow.contentManager
val contentTitle = title?.let {
@@ -206,4 +214,9 @@ class AliInspectionAction : AnAction() {
return PmdGlobalInspectionContextImpl(managerEx.project, managerEx.contentManager, projectScopeSelected)
}
}
+
+ override fun getActionUpdateThread(): ActionUpdateThread {
+ return ActionUpdateThread.BGT
+ }
+
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/PmdGlobalInspectionContextImpl.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/PmdGlobalInspectionContextImpl.kt
index f7c277872..69bd1bc14 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/PmdGlobalInspectionContextImpl.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/PmdGlobalInspectionContextImpl.kt
@@ -116,7 +116,7 @@ class PmdGlobalInspectionContextImpl(
logger.info(file.name + "; scope: " + scope + "; " + virtualFile)
return@tryRunReadActionInSmartMode true
}
- val path = virtualFile.canonicalPath?.toLowerCase() ?: ""
+ val path = virtualFile.canonicalPath?.lowercase() ?: ""
if (!path.endsWith(".java") && !path.endsWith(".vm")) {
return@tryRunReadActionInSmartMode true
}
@@ -227,43 +227,50 @@ class PmdGlobalInspectionContextImpl(
): Future<*>? {
val task: Backgroundable = object : Backgroundable(project, "Scanning Files to Inspect") {
override fun run(indicator: ProgressIndicator) {
- try {
- val fileIndex: FileIndex = ProjectRootManager.getInstance(project).fileIndex
- scope.accept { file: VirtualFile? ->
- ProgressManager.checkCanceled()
- if (isProjectOrWorkspaceFile(file!!) || !fileIndex.isInContent(file)) return@accept true
- val psiFile =
- ReadAction.compute {
- if (project.isDisposed) throw ProcessCanceledException()
- val psi = PsiManager.getInstance(project).findFile(file)
- val document =
- psi?.let { shouldProcess(it, headlessEnvironment, localScopeFiles) }
- if (document != null) {
- return@compute psi
+ ApplicationManager.getApplication().runReadAction(
+ Runnable {
+ try {
+ val fileIndex: FileIndex = ProjectRootManager.getInstance(project).fileIndex
+ scope.accept { file: VirtualFile? ->
+ ProgressManager.checkCanceled()
+ if (isProjectOrWorkspaceFile(file!!) || !fileIndex.isInContent(file)) return@accept true
+ val psiFile =
+ ReadAction.compute {
+ if (project.isDisposed) throw ProcessCanceledException()
+ val psi = PsiManager.getInstance(project).findFile(file)
+ val document =
+ psi?.let { shouldProcess(it, headlessEnvironment, localScopeFiles) }
+ if (document != null) {
+ return@compute psi
+ }
+ null
+ }
+ // do not inspect binary files
+ if (psiFile != null) {
+ try {
+ if (ApplicationManager.getApplication().isReadAccessAllowed) {
+ outFilesToInspect.put(psiFile)
+ }
+ } catch (e: InterruptedException) {
+ logger.error("psiFile interrupted : " + psiFile.name, e)
+ } catch (e: IllegalStateException) {
+ logger.info("psiFile ignored : " + psiFile.name, e)
+ }
}
- null
+ ProgressManager.checkCanceled()
+ true
}
- // do not inspect binary files
- if (psiFile != null) {
+ } catch (e: ProcessCanceledException) {
+ // ignore, but put tombstone
+ } finally {
try {
- check(!ApplicationManager.getApplication().isReadAccessAllowed) { "Must not have read action" }
- outFilesToInspect.put(psiFile)
+ outFilesToInspect.put(PsiUtilCore.NULL_PSI_FILE)
} catch (e: InterruptedException) {
logger.error(e)
}
}
- ProgressManager.checkCanceled()
- true
}
- } catch (e: ProcessCanceledException) {
- // ignore, but put tombstone
- } finally {
- try {
- outFilesToInspect.put(PsiUtilCore.NULL_PSI_FILE)
- } catch (e: InterruptedException) {
- logger.error(e)
- }
- }
+ )
}
}
return (ProgressManager.getInstance() as CoreProgressManager).runProcessWithProgressAsynchronously(
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/SwitchLanguageAction.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/SwitchLanguageAction.kt
index df7d39f00..f4a75344a 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/SwitchLanguageAction.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/SwitchLanguageAction.kt
@@ -20,6 +20,7 @@ import com.alibaba.p3c.idea.i18n.P3cBundle
import com.alibaba.smartfox.idea.common.util.BalloonNotifications
import com.alibaba.smartfox.idea.common.util.getService
import com.intellij.notification.NotificationListener
+import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ex.ApplicationManagerEx
@@ -48,4 +49,9 @@ class SwitchLanguageAction : AnAction(), DumbAware {
override fun update(e: AnActionEvent) {
e.presentation.text = P3cBundle.getMessage("$textKey.cur_${p3cConfig.locale}")
}
+
+ override fun getActionUpdateThread(): ActionUpdateThread {
+ return ActionUpdateThread.EDT
+ }
+
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/ToggleProjectInspectionAction.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/ToggleProjectInspectionAction.kt
index a7ffd0b62..8d9287c10 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/ToggleProjectInspectionAction.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/ToggleProjectInspectionAction.kt
@@ -20,6 +20,7 @@ import com.alibaba.p3c.idea.compatible.inspection.Inspections
import com.alibaba.p3c.idea.config.SmartFoxProjectConfig
import com.alibaba.p3c.idea.i18n.P3cBundle
import com.alibaba.p3c.idea.inspection.AliBaseInspection
+import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.ServiceManager
@@ -37,7 +38,7 @@ class ToggleProjectInspectionAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
- val smartFoxConfig = ServiceManager.getService(project, SmartFoxProjectConfig::class.java)
+ val smartFoxConfig = project.getService(SmartFoxProjectConfig::class.java)
val tools = Inspections.aliInspections(project) {
it.tool is AliBaseInspection
}
@@ -47,7 +48,7 @@ class ToggleProjectInspectionAction : AnAction() {
override fun update(e: AnActionEvent) {
val project = e.project ?: return
- val smartFoxConfig = ServiceManager.getService(project, SmartFoxProjectConfig::class.java)
+ val smartFoxConfig = project.getService(SmartFoxProjectConfig::class.java)
e.presentation.text = if (smartFoxConfig.projectInspectionClosed) {
e.presentation.icon = P3cIcons.PROJECT_INSPECTION_ON
P3cBundle.getMessage("$textKey.open")
@@ -56,4 +57,9 @@ class ToggleProjectInspectionAction : AnAction() {
P3cBundle.getMessage("$textKey.close")
}
}
+
+ override fun getActionUpdateThread(): ActionUpdateThread {
+ return ActionUpdateThread.BGT
+ }
+
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/activity/CommonSettingsApplicationStartupActivity.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/activity/CommonSettingsApplicationStartupActivity.kt
new file mode 100644
index 000000000..abd5af5b7
--- /dev/null
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/activity/CommonSettingsApplicationStartupActivity.kt
@@ -0,0 +1,54 @@
+/*
+ * Copyright 1999-2017 Alibaba Group.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.p3c.idea.activity
+
+import com.alibaba.p3c.idea.config.P3cConfig
+import com.alibaba.p3c.idea.i18n.P3cBundle
+import com.alibaba.p3c.idea.util.HighlightInfoTypes
+import com.alibaba.p3c.idea.util.HighlightSeverities
+import com.xenoamess.p3c.pmd.I18nResources
+import com.alibaba.smartfox.idea.common.activity.AliBaseApplicationStartupActivity
+import com.intellij.codeInsight.daemon.impl.SeverityRegistrar
+import com.intellij.openapi.actionSystem.ActionManager
+import com.intellij.openapi.project.Project
+
+/**
+ *
+ *
+ * @author caikang
+ * @date 2017/06/19
+ */
+class CommonSettingsApplicationStartupActivity : AliBaseApplicationStartupActivity {
+ companion object {
+ const val analyticsGroupId = "com.alibaba.p3c.analytics.action_group"
+ val analyticsGroupText = "$analyticsGroupId.text"
+ private val p3cConfig = P3cConfig()
+ }
+
+ override fun runActivity(project: Project) {
+ SeverityRegistrar.registerStandard(HighlightInfoTypes.BLOCKER, HighlightSeverities.BLOCKER)
+ SeverityRegistrar.registerStandard(HighlightInfoTypes.CRITICAL, HighlightSeverities.CRITICAL)
+ SeverityRegistrar.registerStandard(HighlightInfoTypes.MAJOR, HighlightSeverities.MAJOR)
+
+// Shall not register WARNING and WEAK_WARNING!
+// SeverityRegistrar.registerStandard(HighlightInfoTypes.WARNING, HighlightSeverities.WARNING)
+// SeverityRegistrar.registerStandard(HighlightInfoTypes.WEAK_WARNING, HighlightSeverities.WEAK_WARNING)
+
+ I18nResources.changeLanguage(p3cConfig.locale)
+ val analyticsGroup = ActionManager.getInstance().getAction(analyticsGroupId)
+ analyticsGroup.templatePresentation.text = P3cBundle.getMessage(analyticsGroupText)
+ }
+}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/InspectionProfileService.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/InspectionProfileService.kt
index eff136427..8dd8f7622 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/InspectionProfileService.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/InspectionProfileService.kt
@@ -36,8 +36,11 @@ import java.util.LinkedHashSet
* @date 2017/03/01
*/
object InspectionProfileService {
- fun createSimpleProfile(toolWrapperList: List>,
- managerEx: InspectionManagerEx, psiElement: PsiElement?): InspectionProfileImpl {
+ fun createSimpleProfile(
+ toolWrapperList: List>,
+ managerEx: InspectionManagerEx,
+ psiElement: PsiElement?
+ ): InspectionProfileImpl {
val profile = getProjectInspectionProfile(managerEx.project)
val allWrappers: LinkedHashSet> = Sets.newLinkedHashSet()
allWrappers.addAll(toolWrapperList)
@@ -84,7 +87,11 @@ object InspectionProfileService {
return model
}
- fun toggleInspection(project: Project, aliInspections: List>, closed: Boolean) {
+ fun toggleInspection(
+ project: Project,
+ aliInspections: List>,
+ closed: Boolean
+ ) {
val profile = getProjectInspectionProfile(project)
val shortNames = aliInspections.map {
it.tool.shortName
@@ -102,8 +109,10 @@ object InspectionProfileService {
profile.scopesChanged()
}
- fun setExternalProfile(profile: InspectionProfileImpl,
- inspectionContext: GlobalInspectionContextImpl) {
+ fun setExternalProfile(
+ profile: InspectionProfileImpl,
+ inspectionContext: GlobalInspectionContextImpl
+ ) {
val method = inspectionContext.javaClass.methods.first {
it.name == "setExternalProfile" && it.parameterTypes.size == 1 && it.parameterTypes.first().isAssignableFrom(InspectionProfileImpl::class.java)
}
@@ -111,6 +120,6 @@ object InspectionProfileService {
}
fun getProjectInspectionProfile(project: Project): InspectionProfileImpl {
- return InspectionProjectProfileManager.getInstance(project).inspectionProfile as InspectionProfileImpl
+ return InspectionProjectProfileManager.getInstance(project).currentProfile
}
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/Inspections.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/Inspections.kt
index 1c186c495..fad308363 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/Inspections.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/compatible/inspection/Inspections.kt
@@ -15,12 +15,29 @@
*/
package com.alibaba.p3c.idea.compatible.inspection
+import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListConfig
import com.google.common.base.Splitter
import com.intellij.codeInspection.ex.InspectionProfileImpl
import com.intellij.codeInspection.ex.InspectionToolWrapper
import com.intellij.codeInspection.ex.ScopeToolState
-import com.intellij.codeInspection.javaDoc.JavaDocLocalInspection
import com.intellij.openapi.project.Project
+import com.intellij.openapi.util.JDOMExternalizerUtil
+import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListServiceImpl.P3C_JSON_CONFIG_FILE_NAME
+import com.xenoamess.p3c.pmd.lang.java.util.namelist.NameListServiceImpl.P3C_X8L_CONFIG_FILE_NAME
+import org.apache.commons.lang3.StringUtils
+import org.jdom.Element
+import org.jetbrains.annotations.SystemIndependent
+import java.io.File
+import java.io.FilenameFilter
+
+/**
+ * @author XenoAmess
+ */
+class P3cConfigFilenameFilter : FilenameFilter {
+ override fun accept(dir: File?, name: String?): Boolean {
+ return P3C_X8L_CONFIG_FILE_NAME.equals(name) || P3C_JSON_CONFIG_FILE_NAME.equals(name)
+ }
+}
/**
*
@@ -30,26 +47,52 @@ import com.intellij.openapi.project.Project
*/
object Inspections {
fun aliInspections(project: Project, filter: (InspectionToolWrapper<*, *>) -> Boolean): List> {
+ loadPatchConfigFile(project)
val profile = InspectionProfileService.getProjectInspectionProfile(project)
return getAllTools(project, profile).filter(filter)
}
- fun addCustomTag(project: Project, tag: String) {
- val profile = InspectionProfileService.getProjectInspectionProfile(project)
- val javaDocLocalInspection = profile.getInspectionTool("JavaDoc", project)?.tool
- as? JavaDocLocalInspection ?: return
- if (javaDocLocalInspection.myAdditionalJavadocTags.isEmpty()) {
- javaDocLocalInspection.myAdditionalJavadocTags = tag
- return
+ fun loadPatchConfigFile(project: Project) {
+ val patchConfigFile = fetchPatchConfigFile(project)
+ if (patchConfigFile == null) {
+ NameListConfig.renewNameListService()
+ } else {
+ NameListConfig.renewNameListService(patchConfigFile)
}
+ }
+
+ private fun fetchPatchConfigFile(project: Project): File? {
+ val projectBasePath: @SystemIndependent String? = project.basePath
+ ?: return null
+ val projectBaseFile = File(projectBasePath)
+ val fileList = projectBaseFile.listFiles(P3cConfigFilenameFilter())
+ return if (fileList == null || fileList.isEmpty()) {
+ null
+ } else {
+ fileList[0]
+ }
+ }
+
+
+ fun addCustomTag(project: Project, tag: String) {
+ try {
+ val profile = InspectionProfileService.getProjectInspectionProfile(project)
+ val javaDocLocalInspection : Element = profile.getInspectionTool("JavaDoc", project)?.tool as? Element ?: return
+ val myAdditionalJavadocTags : String? = JDOMExternalizerUtil.readField(javaDocLocalInspection, "myAdditionalJavadocTags")
+ if (StringUtils.isEmpty(myAdditionalJavadocTags)) {
+ JDOMExternalizerUtil.writeField(javaDocLocalInspection, "myAdditionalJavadocTags", tag)
+ return
+ }
- val tags = Splitter.on(',').splitToList(javaDocLocalInspection.myAdditionalJavadocTags)
- if (tags.contains(tag)) {
- return
+ val tags = Splitter.on(',').splitToList(myAdditionalJavadocTags)
+ if (tags.contains(tag)) {
+ return
+ }
+ JDOMExternalizerUtil.writeField(javaDocLocalInspection, "myAdditionalJavadocTags", myAdditionalJavadocTags + ",$tag")
+ profile.profileChanged()
+ profile.scopesChanged()
+ } catch (ignored : Exception) {
}
- javaDocLocalInspection.myAdditionalJavadocTags += "," + tag
- profile.profileChanged()
- profile.scopesChanged()
}
private fun getAllTools(project: Project, profile: InspectionProfileImpl): List> {
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/AliProjectComponent.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/AliProjectComponent.kt
index 4884ea5fb..113852341 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/AliProjectComponent.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/AliProjectComponent.kt
@@ -21,17 +21,17 @@ import com.alibaba.p3c.idea.i18n.P3cBundle
import com.alibaba.p3c.idea.inspection.AliPmdInspectionInvoker
import com.alibaba.p3c.idea.pmd.SourceCodeProcessor
import com.alibaba.p3c.idea.util.withLockNotInline
-import com.alibaba.p3c.pmd.I18nResources
import com.alibaba.smartfox.idea.common.component.AliBaseProjectComponent
+import com.alibaba.smartfox.idea.common.util.getService
import com.intellij.openapi.actionSystem.ActionManager
-import com.intellij.openapi.project.Project
+import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.vfs.VirtualFile
-import com.intellij.openapi.vfs.VirtualFileAdapter
import com.intellij.openapi.vfs.VirtualFileEvent
import com.intellij.openapi.vfs.VirtualFileListener
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.VirtualFileMoveEvent
import com.intellij.psi.PsiManager
+import com.xenoamess.p3c.pmd.I18nResources
import net.sourceforge.pmd.RuleViolation
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.locks.ReentrantReadWriteLock
@@ -40,10 +40,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock
* @author caikang
* @date 2016/12/13
*/
-class AliProjectComponent(
- private val project: Project,
- val p3cConfig: P3cConfig
-) : AliBaseProjectComponent {
+class AliProjectComponent : AliBaseProjectComponent {
private val listener: VirtualFileListener
private val javaExtension = ".java"
private val velocityExtension = ".vm"
@@ -55,10 +52,12 @@ class AliProjectComponent(
private val fileContexts = ConcurrentHashMap()
init {
- listener = object : VirtualFileAdapter() {
+ listener = object : VirtualFileListener {
override fun contentsChanged(event: VirtualFileEvent) {
val path = getFilePath(event) ?: return
+ val project = ProjectManager.getInstance().defaultProject
PsiManager.getInstance(project).findFile(event.file) ?: return
+ val p3cConfig = P3cConfig::class.java.getService()
if (!p3cConfig.ruleCacheEnable) {
AliPmdInspectionInvoker.refreshFileViolationsCache(event.file)
}
@@ -98,12 +97,14 @@ class AliProjectComponent(
}
override fun initComponent() {
+ val p3cConfig = P3cConfig::class.java.getService()
I18nResources.changeLanguage(p3cConfig.locale)
val analyticsGroup = ActionManager.getInstance().getAction(analyticsGroupId)
analyticsGroup.templatePresentation.text = P3cBundle.getMessage(analyticsGroupText)
}
override fun projectOpened() {
+ val project = ProjectManager.getInstance().defaultProject
Inspections.addCustomTag(project, "date")
VirtualFileManager.getInstance().addVirtualFileListener(listener)
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/CommonSettingsApplicationComponent.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/CommonSettingsApplicationComponent.kt
deleted file mode 100644
index 7be5613c8..000000000
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/CommonSettingsApplicationComponent.kt
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright 1999-2017 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.alibaba.p3c.idea.component
-
-import com.alibaba.p3c.idea.util.HighlightInfoTypes
-import com.alibaba.p3c.idea.util.HighlightSeverities
-import com.alibaba.smartfox.idea.common.component.AliBaseApplicationComponent
-import com.intellij.codeInsight.daemon.impl.SeverityRegistrar
-
-/**
- *
- *
- * @author caikang
- * @date 2017/06/19
- */
-class CommonSettingsApplicationComponent : AliBaseApplicationComponent {
- override fun initComponent() {
- SeverityRegistrar.registerStandard(HighlightInfoTypes.BLOCKER, HighlightSeverities.BLOCKER)
- SeverityRegistrar.registerStandard(HighlightInfoTypes.CRITICAL, HighlightSeverities.CRITICAL)
- SeverityRegistrar.registerStandard(HighlightInfoTypes.MAJOR, HighlightSeverities.MAJOR)
- }
-}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/ep/InspectionActionExtensionPoint.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/ep/InspectionActionExtensionPoint.kt
index 0a4c457e7..8309d16f9 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/ep/InspectionActionExtensionPoint.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/ep/InspectionActionExtensionPoint.kt
@@ -34,6 +34,6 @@ interface InspectionActionExtensionPoint {
companion object {
val extension = ExtensionPointName.create(
- "${PluginVersions.pluginId.idString}.inspectionAction")!!
+ "${PluginVersions.pluginId.idString}.inspectionAction")
}
}
\ No newline at end of file
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/i18n/P3cBundle.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/i18n/P3cBundle.kt
index cbd83e8d4..9439f71a8 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/i18n/P3cBundle.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/i18n/P3cBundle.kt
@@ -16,11 +16,13 @@
package com.alibaba.p3c.idea.i18n
import com.alibaba.p3c.idea.config.P3cConfig
-import com.alibaba.p3c.pmd.I18nResources
+import com.xenoamess.p3c.pmd.I18nResources
import com.alibaba.smartfox.idea.common.util.getService
-import com.intellij.CommonBundle
+import com.intellij.AbstractBundle
+import com.intellij.openapi.application.CachedSingletonsRegistry
import java.util.Locale
import java.util.ResourceBundle
+import java.util.function.Supplier
/**
*
@@ -29,15 +31,23 @@ import java.util.ResourceBundle
* @date 2017/06/20
*/
object P3cBundle {
- private val p3cConfig = P3cConfig::class.java.getService()
- private val resourceBundle = ResourceBundle.getBundle("messages.P3cBundle",
- Locale(p3cConfig.locale), I18nResources.XmlControl())
+ private val p3cConfigSupplier: Supplier =
+ CachedSingletonsRegistry.lazy {
+ P3cConfig::class.java.getService()
+ }
+ private val resourceBundleSupplier =
+ CachedSingletonsRegistry.lazy {
+ ResourceBundle.getBundle(
+ "messages.P3cBundle",
+ Locale(p3cConfigSupplier.get().locale), I18nResources.XmlControl()
+ )
+ }
fun getMessage(key: String): String {
- return resourceBundle.getString(key).trim()
+ return resourceBundleSupplier.get().getString(key).trim()
}
fun message(key: String, vararg params: Any): String {
- return CommonBundle.message(resourceBundle, key, *params).trim()
+ return AbstractBundle.message(resourceBundleSupplier.get(), key, *params).trim()
}
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliAccessToNonThreadSafeStaticFieldFromInstanceInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliAccessToNonThreadSafeStaticFieldFromInstanceInspection.kt
index 9f01b7e3a..339c87473 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliAccessToNonThreadSafeStaticFieldFromInstanceInspection.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliAccessToNonThreadSafeStaticFieldFromInstanceInspection.kt
@@ -27,6 +27,7 @@ class AliAccessToNonThreadSafeStaticFieldFromInstanceInspection
: AccessToNonThreadSafeStaticFieldFromInstanceInspection,
AliBaseInspection {
constructor()
+
/**
* For Javassist
*/
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliArrayNamingShouldHaveBracketInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliArrayNamingShouldHaveBracketInspection.kt
index 3fbd2e4a4..5ad9b81da 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliArrayNamingShouldHaveBracketInspection.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliArrayNamingShouldHaveBracketInspection.kt
@@ -35,6 +35,7 @@ import javax.swing.JComponent
*/
class AliArrayNamingShouldHaveBracketInspection : CStyleArrayDeclarationInspection, AliBaseInspection {
constructor()
+
/**
* ForJavassist
*/
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliBaseInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliBaseInspection.kt
index a674ee347..fc0e71c8a 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliBaseInspection.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliBaseInspection.kt
@@ -65,18 +65,22 @@ interface AliBaseInspection {
/**
* inspection short name
- * @return shor name
+ * @return short name
*/
fun getShortName(): String
fun manualBuildFix(psiElement: PsiElement, isOnTheFly: Boolean): LocalQuickFix? = null
- fun manualParsePsiElement(psiFile: PsiFile, manager: InspectionManager,
- start: Int, end: Int): PsiElement {
+ fun manualParsePsiElement(
+ psiFile: PsiFile,
+ manager: InspectionManager,
+ start: Int,
+ end: Int
+ ): PsiElement {
return psiFile.findElementAt(start)!!
}
companion object {
- val GROUP_NAME = "Ali-Check"
+ const val GROUP_NAME = "Ali-Check"
}
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliControlFlowStatementWithoutBracesInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliControlFlowStatementWithoutBracesInspection.kt
index 8a5d7ec7f..830d84f7e 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliControlFlowStatementWithoutBracesInspection.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliControlFlowStatementWithoutBracesInspection.kt
@@ -32,6 +32,7 @@ class AliControlFlowStatementWithoutBracesInspection
: ControlFlowStatementWithoutBracesInspection,
AliBaseInspection {
constructor()
+
/**
* For Javassist
*/
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliEqualsAvoidNullInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliEqualsAvoidNullInspection.kt
index 2e7e5f55d..aa4569c6a 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliEqualsAvoidNullInspection.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliEqualsAvoidNullInspection.kt
@@ -42,6 +42,7 @@ import org.jetbrains.annotations.NonNls
*/
class AliEqualsAvoidNullInspection : LiteralAsArgToStringEqualsInspection, AliBaseInspection {
constructor()
+
/**
* For Javassist
*/
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLocalInspectionToolProvider.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLocalInspectionToolProvider.kt
index 22e314567..fa519fe58 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLocalInspectionToolProvider.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLocalInspectionToolProvider.kt
@@ -20,7 +20,6 @@ import com.alibaba.p3c.idea.inspection.standalone.AliAccessStaticViaInstanceInsp
import com.alibaba.p3c.idea.inspection.standalone.AliDeprecationInspection
import com.alibaba.p3c.idea.inspection.standalone.AliMissingOverrideAnnotationInspection
import com.alibaba.p3c.idea.inspection.standalone.MapOrSetKeyShouldOverrideHashCodeEqualsInspection
-import com.alibaba.p3c.pmd.I18nResources
import com.alibaba.smartfox.idea.common.util.getService
import com.beust.jcommander.internal.Lists
import com.beust.jcommander.internal.Maps
@@ -32,6 +31,7 @@ import com.intellij.psi.PsiCompiledFile
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiImportList
import com.intellij.psi.PsiJavaFile
+import com.xenoamess.p3c.pmd.I18nResources
import javassist.CannotCompileException
import javassist.ClassClassPath
import javassist.ClassPool
@@ -40,7 +40,6 @@ import javassist.NotFoundException
import net.sourceforge.pmd.Rule
import net.sourceforge.pmd.RuleSet
import net.sourceforge.pmd.RuleSetFactory
-import net.sourceforge.pmd.RuleSetNotFoundException
import net.sourceforge.pmd.RuleSets
import javax.annotation.Generated
@@ -67,9 +66,9 @@ class AliLocalInspectionToolProvider : InspectionToolProvider {
class RuleInfo(var rule: Rule, var shouldInspectChecker: ShouldInspectChecker)
companion object {
- val ruleInfoMap: MutableMap = Maps.newHashMap()
+ val ruleInfoMap: MutableMap = Maps.newHashMap()
private val LOGGER = Logger.getInstance(AliLocalInspectionToolProvider::class.java)
- val ruleNames: MutableList = Lists.newArrayList()!!
+ val ruleNames: MutableList = Lists.newArrayList()!!
private val CLASS_LIST = Lists.newArrayList>()
private val nativeInspectionToolClass = arrayListOf>(
AliMissingOverrideAnnotationInspection::class.java,
@@ -139,7 +138,7 @@ class AliLocalInspectionToolProvider : InspectionToolProvider {
private fun initPmdInspection() {
for (ri in newRuleInfos()) {
this.ruleNames.add(ri.rule.name)
- ruleInfoMap.put(ri.rule.name, ri)
+ ruleInfoMap[ri.rule.name] = ri
}
val pool = ClassPool.getDefault()
pool.insertClassPath(ClassClassPath(DelegatePmdInspection::class.java))
@@ -199,8 +198,8 @@ class AliLocalInspectionToolProvider : InspectionToolProvider {
ruleSet.rules.mapTo(result) {
RuleInfo(it, shouldInspectChecker)
}
- } catch (e: RuleSetNotFoundException) {
- LOGGER.error(String.format("rule set %s not found for", ruleSetName))
+ } catch (e: Exception) {
+ LOGGER.error(String.format("rule set %s load failed for", ruleSetName))
}
return result
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLongLiteralsEndingWithLowercaseLInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLongLiteralsEndingWithLowercaseLInspection.kt
index c1fa74620..8fe49de6a 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLongLiteralsEndingWithLowercaseLInspection.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliLongLiteralsEndingWithLowercaseLInspection.kt
@@ -33,6 +33,7 @@ import com.siyeh.ig.numeric.LongLiteralsEndingWithLowercaseLInspection
*/
class AliLongLiteralsEndingWithLowercaseLInspection : LongLiteralsEndingWithLowercaseLInspection, AliBaseInspection {
constructor()
+
/**
* For Javassist
*/
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspection.kt
index a6731bead..846cecf11 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspection.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspection.kt
@@ -99,7 +99,7 @@ class AliPmdInspection(private val ruleName: String) : LocalInspectionTool(),
override fun getShortName(): String {
- var shortName = "Alibaba" + ruleName
+ var shortName = "Alibaba$ruleName"
val index = shortName.lastIndexOf("Rule")
if (index > NumberConstants.INDEX_0) {
shortName = shortName.substring(NumberConstants.INDEX_0, index)
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspectionInvoker.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspectionInvoker.kt
index 6b57f75e3..3ede1be59 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspectionInvoker.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspectionInvoker.kt
@@ -21,7 +21,7 @@ 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.ProblemsUtils
-import com.alibaba.p3c.pmd.lang.java.rule.comment.RemoveCommentedCodeRule
+import com.xenoamess.p3c.pmd.lang.java.rule.comment.RemoveCommentedCodeRule
import com.beust.jcommander.internal.Lists
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
@@ -43,9 +43,9 @@ import java.util.concurrent.TimeUnit
* @date 2016/12/13
*/
class AliPmdInspectionInvoker(
- private val psiFile: PsiFile,
- private val manager: InspectionManager,
- private val rule: Rule
+ private val psiFile: PsiFile,
+ private val manager: InspectionManager,
+ private val rule: Rule
) {
private val logger = Logger.getInstance(javaClass)
@@ -75,9 +75,12 @@ class AliPmdInspectionInvoker(
}
val problemDescriptors = Lists.newArrayList(violations.size)
for (rv in violations) {
- val virtualFile = LocalFileSystem.getInstance().findFileByPath(rv.filename) ?: continue
- val psiFile = PsiManager.getInstance(manager.project).findFile(virtualFile) ?: continue
- val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: continue
+ val virtualFile = LocalFileSystem.getInstance().findFileByPath(rv.filename)
+ ?: continue
+ val psiFile = PsiManager.getInstance(manager.project).findFile(virtualFile)
+ ?: continue
+ val document = FileDocumentManager.getInstance().getDocument(virtualFile)
+ ?: continue
val offsets = if (rv.rule.name == RemoveCommentedCodeRule::class.java.simpleName) {
Offsets(
@@ -96,8 +99,14 @@ class AliPmdInspectionInvoker(
"${rv.description} (line ${rv.beginLine})"
}
val problemDescriptor = ProblemsUtils.createProblemDescriptorForPmdRule(
- psiFile, manager,
- isOnTheFly, rv.rule.name, errorMessage, offsets.start, offsets.end, rv.beginLine
+ psiFile,
+ manager,
+ isOnTheFly,
+ rv.rule.name,
+ errorMessage,
+ offsets.start,
+ offsets.end,
+ rv.beginLine
) ?: continue
problemDescriptors.add(problemDescriptor)
}
@@ -113,8 +122,10 @@ class AliPmdInspectionInvoker(
}
fun invokeInspection(
- psiFile: PsiFile?, manager: InspectionManager, rule: Rule,
- isOnTheFly: Boolean
+ psiFile: PsiFile?,
+ manager: InspectionManager,
+ rule: Rule,
+ isOnTheFly: Boolean
): Array? {
if (psiFile == null) {
return null
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliWrapperTypeEqualityInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliWrapperTypeEqualityInspection.kt
index 25ac033c5..d549025ee 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliWrapperTypeEqualityInspection.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliWrapperTypeEqualityInspection.kt
@@ -113,7 +113,7 @@ class AliWrapperTypeEqualityInspection : BaseInspection, AliBaseInspection {
return true
}
return TypeUtils.expressionHasTypeOrSubtype(expression, CommonClassNames.JAVA_LANG_BOOLEAN)
- || TypeUtils.expressionHasTypeOrSubtype(expression, CommonClassNames.JAVA_LANG_CHARACTER)
+ || TypeUtils.expressionHasTypeOrSubtype(expression, CommonClassNames.JAVA_LANG_CHARACTER)
}
private fun hasNumberType(expression: PsiExpression): Boolean {
@@ -126,13 +126,13 @@ class AliWrapperTypeEqualityInspection : BaseInspection, AliBaseInspection {
}
private class ArrayEqualityFix(private val deepEquals: Boolean, private val familyName: String) :
- InspectionGadgetsFix() {
+ InspectionGadgetsFix() {
override fun getName(): String {
- if (deepEquals) {
- return "$replaceWith 'Arrays.deepEquals()'"
+ return if (deepEquals) {
+ "$replaceWith 'Arrays.deepEquals()'"
} else {
- return "$replaceWith 'Arrays.equals()'"
+ "$replaceWith 'Arrays.equals()'"
}
}
@@ -145,6 +145,7 @@ class AliWrapperTypeEqualityInspection : BaseInspection, AliBaseInspection {
val element = descriptor.psiElement
val parent = element.parent as? PsiBinaryExpression ?: return
val tokenType = parent.operationTokenType
+
@NonNls
val newExpressionText = StringBuilder()
if (JavaTokenType.NE == tokenType) {
@@ -163,14 +164,15 @@ class AliWrapperTypeEqualityInspection : BaseInspection, AliBaseInspection {
newExpressionText.append(rhs.text)
newExpressionText.append(')')
PsiReplacementUtil.replaceExpressionAndShorten(
- parent,
- newExpressionText.toString()
+ parent,
+ newExpressionText.toString()
)
}
}
override fun manualBuildFix(psiElement: PsiElement, isOnTheFly: Boolean): LocalQuickFix? {
- val expression = psiElement.parent as? PsiBinaryExpression ?: return null
+ val expression = psiElement.parent as? PsiBinaryExpression
+ ?: return null
val rhs = expression.rOperand ?: return null
val lhs = expression.lOperand
val lhsType = lhs.type
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegateLocalInspectionTool.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegateLocalInspectionTool.kt
index b199f4a03..18e161bcf 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegateLocalInspectionTool.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegateLocalInspectionTool.kt
@@ -46,9 +46,10 @@ class DelegateLocalInspectionTool : LocalInspectionTool(), AliBaseInspection {
}
override fun checkFile(
- file: PsiFile, manager: InspectionManager,
- isOnTheFly: Boolean
- ): Array? {
+ file: PsiFile,
+ manager: InspectionManager,
+ isOnTheFly: Boolean
+ ): Array? {
return localInspectionTool.checkFile(file, manager, isOnTheFly)
}
@@ -87,8 +88,9 @@ class DelegateLocalInspectionTool : LocalInspectionTool(), AliBaseInspection {
}
override fun buildVisitor(
- holder: ProblemsHolder, isOnTheFly: Boolean,
- session: LocalInspectionToolSession
+ holder: ProblemsHolder,
+ isOnTheFly: Boolean,
+ session: LocalInspectionToolSession
): PsiElementVisitor {
if (!AliLocalInspectionToolProvider.javaShouldInspectChecker.shouldInspect(holder.file)) {
return PsiElementVisitor.EMPTY_VISITOR
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegatePmdInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegatePmdInspection.kt
index 910bd2534..82fdb3c5c 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegatePmdInspection.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/DelegatePmdInspection.kt
@@ -42,8 +42,11 @@ class DelegatePmdInspection : LocalInspectionTool(), AliBaseInspection, PmdRuleI
return aliPmdInspection.runForWholeFile()
}
- override fun checkFile(file: PsiFile, manager: InspectionManager,
- isOnTheFly: Boolean): Array? {
+ override fun checkFile(
+ file: PsiFile,
+ manager: InspectionManager,
+ isOnTheFly: Boolean
+ ): Array? {
return aliPmdInspection.checkFile(file, manager, isOnTheFly)
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/PmdRuleInspectionIdentify.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/PmdRuleInspectionIdentify.kt
index b84b5bd36..c3043f366 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/PmdRuleInspectionIdentify.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/PmdRuleInspectionIdentify.kt
@@ -22,5 +22,4 @@ package com.alibaba.p3c.idea.inspection
* @date 2017/03/16
6
*/
-interface PmdRuleInspectionIdentify {
-}
\ No newline at end of file
+interface PmdRuleInspectionIdentify
\ No newline at end of file
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/RuleInspectionUtils.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/RuleInspectionUtils.kt
index 3f0693d76..05d7b4e04 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/RuleInspectionUtils.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/RuleInspectionUtils.kt
@@ -18,7 +18,7 @@ package com.alibaba.p3c.idea.inspection
import com.alibaba.p3c.idea.config.P3cConfig
import com.alibaba.p3c.idea.util.HighlightDisplayLevels
import com.alibaba.p3c.idea.util.NumberConstants
-import com.alibaba.p3c.pmd.I18nResources
+import com.xenoamess.p3c.pmd.I18nResources
import com.alibaba.smartfox.idea.common.util.getService
import com.google.common.base.Joiner
import com.google.common.collect.ImmutableMap
@@ -59,7 +59,7 @@ object RuleInspectionUtils {
cfg.getTemplate("StaticDescriptionTemplate.ftl")
}
- private val ruleSetsPrefix = "rulesets/"
+ private const val ruleSetsPrefix = "rulesets/"
private val ruleStaticDescriptions: Map
private val ruleMessages: Map
@@ -92,10 +92,12 @@ object RuleInspectionUtils {
}
fun getHighlightDisplayLevel(rulePriority: RulePriority): HighlightDisplayLevel {
- when (rulePriority) {
- RulePriority.HIGH -> return HighlightDisplayLevels.BLOCKER
- RulePriority.MEDIUM_HIGH -> return HighlightDisplayLevels.CRITICAL
- else -> return HighlightDisplayLevels.MAJOR
+ return when (rulePriority) {
+ RulePriority.HIGH -> HighlightDisplayLevels.BLOCKER
+ RulePriority.MEDIUM_HIGH -> HighlightDisplayLevels.CRITICAL
+ RulePriority.MEDIUM -> HighlightDisplayLevels.MAJOR
+ RulePriority.MEDIUM_LOW -> HighlightDisplayLevels.WARNING
+ else -> HighlightDisplayLevels.WEAK_WARNING
}
}
@@ -107,15 +109,14 @@ object RuleInspectionUtils {
val writer = StringWriter()
try {
val map = Maps.newHashMap()
- map.put("message", StringUtils.trimToEmpty(rule.message))
- map.put("description", StringUtils.trimToEmpty(rule.description))
+ map["message"] = StringUtils.trimToEmpty(rule.message)
+ map["description"] = StringUtils.trimToEmpty(rule.description)
val examples = rule.examples.map {
- it?.trim {
- c ->
+ it?.trim { c ->
c == '\n'
}
}
- map.put("examples", examples)
+ map["examples"] = examples
staticDescriptionTemplate.process(map, writer)
} catch (e: TemplateException) {
logger.error(e)
@@ -136,7 +137,7 @@ object RuleInspectionUtils {
ruleSets.allRuleSets
.asSequence()
.flatMap { it.rules.asSequence() }
- .forEach { map.put(it.name, it) }
+ .forEach { map[it.name] = it }
return Lists.newArrayList(map.values)
} catch (e: IOException) {
logger.warn("no available alibaba rules")
@@ -175,21 +176,21 @@ object RuleInspectionUtils {
@Throws(IOException::class)
private fun findRuleSetsFromJar(ruleSets: MutableList, url: URL) {
- logger.info("start to find rule sets from jar " + url)
+ logger.info("start to find rule sets from jar $url")
var path = URLDecoder.decode(url.path, StandardCharsets.UTF_8.name())
val index = path.lastIndexOf(URLUtil.JAR_SEPARATOR)
if (index > NumberConstants.INDEX_0) {
path = path.substring("file:".length, index)
}
val jarFile = JarFile(path)
- logger.info("create jarFile for path " + path)
+ logger.info("create jarFile for path $path")
val jarEntries = jarFile.entries()
while (jarEntries.hasMoreElements()) {
val jarEntry = jarEntries.nextElement()
val subPath = jarEntry.name.replace(ruleSetsPrefix, "")
if (ruleSetFilePattern.matcher(subPath).find()) {
val resultPath = subPath.replace(".xml", "")
- logger.info("get result rule set " + resultPath)
+ logger.info("get result rule set $resultPath")
ruleSets.add(resultPath)
}
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliAccessStaticViaInstanceInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliAccessStaticViaInstanceInspection.kt
index ba5001e46..005167e69 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliAccessStaticViaInstanceInspection.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliAccessStaticViaInstanceInspection.kt
@@ -26,19 +26,10 @@ import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil
import com.intellij.codeInsight.daemon.impl.quickfix.AccessStaticViaInstanceFix
import com.intellij.codeInsight.daemon.impl.quickfix.RemoveUnusedVariableUtil
+import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.accessStaticViaInstance.AccessStaticViaInstance
-import com.intellij.psi.JavaElementVisitor
-import com.intellij.psi.JavaResolveResult
-import com.intellij.psi.PsiClass
-import com.intellij.psi.PsiElement
-import com.intellij.psi.PsiElementVisitor
-import com.intellij.psi.PsiMember
-import com.intellij.psi.PsiModifier
-import com.intellij.psi.PsiPackage
-import com.intellij.psi.PsiReferenceExpression
-import com.intellij.psi.PsiSubstitutor
-import java.util.ArrayList
+import com.intellij.psi.*
/**
* @author caikang
@@ -48,6 +39,7 @@ class AliAccessStaticViaInstanceInspection : AccessStaticViaInstance, AliBaseIns
val messageKey = "com.alibaba.p3c.idea.inspection.standalone.AliAccessStaticViaInstanceInspection"
constructor()
+
/**
* For Javassist
*/
@@ -69,16 +61,12 @@ class AliAccessStaticViaInstanceInspection : AccessStaticViaInstance, AliBaseIns
return "AliAccessStaticViaInstance"
}
- override fun createAccessStaticViaInstanceFix(expr: PsiReferenceExpression,
- onTheFly: Boolean,
- result: JavaResolveResult): AccessStaticViaInstanceFix {
- return object : AccessStaticViaInstanceFix(expr, result, onTheFly) {
+ override fun createAccessStaticViaInstanceFix(
+ expr: PsiReferenceExpression,
+ result: JavaResolveResult
+ ): LocalQuickFix {
+ val accessStaticViaInstanceFix : AccessStaticViaInstanceFix = object : AccessStaticViaInstanceFix(expr, result) {
val fixKey = "com.alibaba.p3c.idea.quickfix.standalone.AliAccessStaticViaInstanceInspection"
- internal val text = calcText(result.element as PsiMember, result.substitutor)
-
- override fun getText(): String {
- return text
- }
private fun calcText(member: PsiMember, substitutor: PsiSubstitutor): String {
val aClass = member.containingClass ?: return ""
@@ -93,6 +81,7 @@ class AliAccessStaticViaInstanceInspection : AccessStaticViaInstance, AliBaseIns
}
}
}
+ return LocalQuickFix.from(accessStaticViaInstanceFix) as LocalQuickFix
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
@@ -107,9 +96,17 @@ class AliAccessStaticViaInstanceInspection : AccessStaticViaInstance, AliBaseIns
return HighlightDisplayLevels.BLOCKER
}
- private fun checkAccessStaticMemberViaInstanceReference(expr: PsiReferenceExpression, holder: ProblemsHolder,
- onTheFly: Boolean) {
- val result = expr.advancedResolve(false)
+ private fun checkAccessStaticMemberViaInstanceReference(
+ expr: PsiReferenceExpression,
+ holder: ProblemsHolder,
+ onTheFly: Boolean
+ ) {
+ val result:JavaResolveResult;
+ try {
+ result = expr.advancedResolve(false)
+ } catch (e: Exception) {
+ return
+ }
val resolved = result.element as? PsiMember ?: return
val qualifierExpression = expr.qualifierExpression ?: return
@@ -129,12 +126,12 @@ class AliAccessStaticViaInstanceInspection : AccessStaticViaInstance, AliBaseIns
"${JavaHighlightUtil.formatType(qualifierExpression.type)}.${HighlightMessageUtil.getSymbolName(
resolved, result.substitutor)}")
if (!onTheFly) {
- if (RemoveUnusedVariableUtil.checkSideEffects(qualifierExpression, null, ArrayList())) {
+ if (RemoveUnusedVariableUtil.checkSideEffects(qualifierExpression, null, ArrayList())) {
holder.registerProblem(expr, description)
return
}
}
- holder.registerProblem(expr, description, createAccessStaticViaInstanceFix(expr, onTheFly, result))
+ holder.registerProblem(expr, description, createAccessStaticViaInstanceFix(expr, result))
}
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliDeprecationInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliDeprecationInspection.kt
index 78532cc2a..a4f7eea9a 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliDeprecationInspection.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliDeprecationInspection.kt
@@ -40,6 +40,7 @@ class AliDeprecationInspection : DeprecationInspection, AliBaseInspection {
private val messageKey = "com.alibaba.p3c.idea.inspection.standalone.AliDeprecationInspection"
constructor()
+
/**
* For Javassist
*/
@@ -87,40 +88,82 @@ class AliDeprecationInspection : DeprecationInspection, AliBaseInspection {
class DeprecationInspectionProblemsHolder(private val holder: ProblemsHolder, onTheFly: Boolean) : ProblemsHolder(
holder.manager, holder.file, onTheFly) {
- override fun registerProblem(psiElement: PsiElement,
+ override fun registerProblem(
+ psiElement: PsiElement,
@Nls descriptionTemplate: String,
- fixes: Array?) {
- holder.registerProblem(psiElement, getMessage(descriptionTemplate), *(fixes ?: emptyArray()))
+ fixes: Array?
+ ) {
+ holder.registerProblem(
+ psiElement,
+ getMessage(descriptionTemplate),
+ *(fixes ?: emptyArray())
+ )
}
- override fun registerProblem(psiElement: PsiElement,
+ override fun registerProblem(
+ psiElement: PsiElement,
@Nls descriptionTemplate: String,
- highlightType: ProblemHighlightType, fixes: Array?) {
- holder.registerProblem(psiElement, getMessage(descriptionTemplate), highlightType, *(fixes ?: emptyArray()))
+ highlightType: ProblemHighlightType,
+ fixes: Array?
+ ) {
+ holder.registerProblem(
+ psiElement,
+ getMessage(descriptionTemplate),
+ highlightType,
+ *(fixes ?: emptyArray())
+ )
}
- override fun registerProblem(reference: PsiReference, descriptionTemplate: String,
- highlightType: ProblemHighlightType) {
+ override fun registerProblem(
+ reference: PsiReference,
+ descriptionTemplate: String,
+ highlightType: ProblemHighlightType
+ ) {
holder.registerProblem(reference, getMessage(descriptionTemplate), highlightType)
}
- override fun registerProblemForReference(reference: PsiReference,
- highlightType: ProblemHighlightType, descriptionTemplate: String,
- fixes: Array?) {
- holder.registerProblemForReference(reference, highlightType, getMessage(descriptionTemplate),
- *(fixes ?: emptyArray()))
+ override fun registerProblemForReference(
+ reference: PsiReference,
+ highlightType: ProblemHighlightType,
+ descriptionTemplate: String,
+ fixes: Array?
+ ) {
+ holder.registerProblemForReference(
+ reference,
+ highlightType,
+ getMessage(descriptionTemplate),
+ *(fixes ?: emptyArray())
+ )
}
- override fun registerProblem(psiElement: PsiElement, rangeInElement: TextRange?,
- message: String, fixes: Array?) {
- holder.registerProblem(psiElement, rangeInElement, getMessage(message), *(fixes ?: emptyArray()))
+ override fun registerProblem(
+ psiElement: PsiElement,
+ rangeInElement: TextRange?,
+ message: String,
+ fixes: Array?
+ ) {
+ holder.registerProblem(
+ psiElement,
+ rangeInElement,
+ getMessage(message),
+ *(fixes ?: emptyArray())
+ )
}
- override fun registerProblem(psiElement: PsiElement, message: String,
- highlightType: ProblemHighlightType, rangeInElement: TextRange?,
- fixes: Array?) {
- holder.registerProblem(psiElement, getMessage(message), highlightType, rangeInElement,
- *(fixes ?: emptyArray()))
+ override fun registerProblem(
+ psiElement: PsiElement,
+ message: String,
+ highlightType: ProblemHighlightType,
+ rangeInElement: TextRange?,
+ fixes: Array?
+ ) {
+ holder.registerProblem(
+ psiElement,
+ getMessage(message),
+ highlightType,
+ rangeInElement,
+ *(fixes ?: emptyArray())
+ )
}
private fun getMessage(msg: String): String {
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliMissingOverrideAnnotationInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliMissingOverrideAnnotationInspection.kt
index 9b4d0070d..22a1084b3 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliMissingOverrideAnnotationInspection.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliMissingOverrideAnnotationInspection.kt
@@ -44,6 +44,7 @@ class AliMissingOverrideAnnotationInspection : MissingOverrideAnnotationInspecti
private val messageKey = "com.alibaba.p3c.idea.inspection.standalone.AliMissingOverrideAnnotationInspection"
constructor()
+
/**
* For Javassist
*/
@@ -64,10 +65,17 @@ class AliMissingOverrideAnnotationInspection : MissingOverrideAnnotationInspecti
override fun createOptionsPanel(): JComponent? = null
- override fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
- val fix = super.buildFix(*infos) ?: return null
- return DecorateInspectionGadgetsFix(fix,
- P3cBundle.getMessage("com.alibaba.p3c.idea.quickfix.standalone.AliMissingOverrideAnnotationInspection"))
+ override protected fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
+ val fix : LocalQuickFix
+ try {
+ fix = super.buildFix(*infos) ?: return null
+ } catch (e: Exception){
+ return null;
+ }
+ return DecorateInspectionGadgetsFix(
+ fix,
+ P3cBundle.getMessage("com.alibaba.p3c.idea.quickfix.standalone.AliMissingOverrideAnnotationInspection")
+ )
}
override fun manualBuildFix(psiElement: PsiElement, isOnTheFly: Boolean): LocalQuickFix? = buildFix(psiElement)
@@ -98,12 +106,18 @@ class AliMissingOverrideAnnotationInspection : MissingOverrideAnnotationInspecti
if (!isJdk6Override(method, methodClass) && !isJdk5Override(method, methodClass)) {
return
}
- if (ignoreObjectMethods && (MethodUtils.isHashCode(method) ||
- MethodUtils.isEquals(method) ||
- MethodUtils.isToString(method))) {
+ if (ignoreObjectMethods
+ &&
+ (MethodUtils.isHashCode(method)
+ ||
+ MethodUtils.isEquals(method)
+ ||
+ MethodUtils.isToString(method)
+ )
+ ) {
return
}
- registerMethodError(method)
+ this.registerMethodError(method, *arrayOf(method, true, true))
}
private fun hasOverrideAnnotation(element: PsiModifierListOwner): Boolean {
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/MapOrSetKeyShouldOverrideHashCodeEqualsInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/MapOrSetKeyShouldOverrideHashCodeEqualsInspection.kt
index 6eea27134..3d07c4daa 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/MapOrSetKeyShouldOverrideHashCodeEqualsInspection.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/MapOrSetKeyShouldOverrideHashCodeEqualsInspection.kt
@@ -33,6 +33,7 @@ import com.intellij.psi.PsiVariable
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.BaseInspectionVisitor
import org.jetbrains.annotations.NonNls
+import java.util.Locale
/**
* @author caikang
@@ -81,14 +82,14 @@ class MapOrSetKeyShouldOverrideHashCodeEqualsInspection : BaseInspection, AliBas
override fun toString(): String {
val string = super.toString()
- return string[0] + string.substring(1).toLowerCase()
+ return string[0] + string.substring(1).lowercase()
}
}
private class MapOrSetKeyVisitor : BaseInspectionVisitor() {
private fun getClassType(aClass: PsiClass?): ClassType {
- return isMapOrSet(aClass, Sets.newHashSet())
+ return isMapOrSet(aClass, Sets.newHashSet())
}
private fun isMapOrSet(aClass: PsiClass?, visitedClasses: MutableSet): ClassType {
@@ -171,8 +172,8 @@ class MapOrSetKeyShouldOverrideHashCodeEqualsInspection : BaseInspection, AliBas
companion object {
- private val skipJdkPackageJava = "java."
- private val skipJdkPackageJavax = "javax."
+ private const val skipJdkPackageJava = "java."
+ private const val skipJdkPackageJavax = "javax."
private fun redefineHashCodeEquals(psiType: PsiType): Boolean {
if (psiType !is PsiClassType) {
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/AliPmdProcessor.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/AliPmdProcessor.kt
index 76557d40f..bee7f88e8 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/AliPmdProcessor.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/AliPmdProcessor.kt
@@ -15,6 +15,7 @@
*/
package com.alibaba.p3c.idea.pmd
+import com.alibaba.p3c.idea.compatible.inspection.Inspections
import com.alibaba.p3c.idea.component.AliProjectComponent
import com.google.common.base.Throwables
import com.intellij.openapi.application.ex.ApplicationUtil
@@ -52,6 +53,7 @@ class AliPmdProcessor private constructor(val rule: Rule? = null, val ruleSets:
}
fun processFile(psiFile: PsiFile, isOnTheFly: Boolean): List {
+ Inspections.loadPatchConfigFile(psiFile.project)
configuration.setSourceEncoding(psiFile.virtualFile.charset.name())
configuration.inputPaths = psiFile.virtualFile.canonicalPath
val document = FileDocumentManager.getInstance().getDocument(psiFile.virtualFile) ?: return emptyList()
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/SourceCodeProcessor.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/SourceCodeProcessor.kt
index aae6148c8..985faca4c 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/SourceCodeProcessor.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/SourceCodeProcessor.kt
@@ -26,6 +26,10 @@ import net.sourceforge.pmd.lang.LanguageVersionHandler
import net.sourceforge.pmd.lang.Parser
import net.sourceforge.pmd.lang.ast.Node
import net.sourceforge.pmd.lang.ast.ParseException
+import net.sourceforge.pmd.lang.xpath.Initializer
+import java.io.IOException
+import java.io.InputStream
+import java.io.InputStreamReader
import java.io.Reader
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit.MILLISECONDS
@@ -60,6 +64,15 @@ class SourceCodeProcessor(
@Throws(PMDException::class)
fun processSourceCode(sourceCode: Reader, ruleSets: RuleSets, ctx: RuleContext) {
determineLanguage(ctx)
+
+ // make sure custom XPath functions are initialized
+ Initializer.initialize()
+
+ processSourceCodeWithoutCache(sourceCode, ruleSets, ctx)
+ }
+
+ @Throws(PMDException::class)
+ private fun processSourceCodeWithoutCache(sourceCode: Reader, ruleSets: RuleSets, ctx: RuleContext) {
try {
ruleSets.start(ctx)
processSource(sourceCode, ruleSets, ctx)
@@ -143,6 +156,7 @@ class SourceCodeProcessor(
val languageVersionHandler = languageVersion.languageVersionHandler
val parser = PMD.parserFor(languageVersion, configuration)
val rootNode = parse(ctx, sourceCode, parser)
+ resolveQualifiedNames(rootNode, languageVersionHandler)
symbolFacade(rootNode, languageVersionHandler)
val language = languageVersion.language
usesDFA(languageVersion, rootNode, ruleSets, language)
@@ -181,20 +195,25 @@ class SourceCodeProcessor(
}
private fun usesTypeResolution(
- languageVersion: LanguageVersion, rootNode: Node, ruleSets: RuleSets,
- language: Language
+ languageVersion: LanguageVersion,
+ rootNode: Node,
+ ruleSets: RuleSets,
+ language: Language
) {
if (ruleSets.usesTypeResolution(language)) {
TimeTracker.startOperation(TimedOperationCategory.TYPE_RESOLUTION).use { to ->
languageVersion.languageVersionHandler.getTypeResolutionFacade(configuration.classLoader)
- .start(rootNode)
+ .start(rootNode)
}
}
}
+
private fun usesMultifile(
- rootNode: Node, languageVersionHandler: LanguageVersionHandler, ruleSets: RuleSets,
+ rootNode: Node,
+ languageVersionHandler: LanguageVersionHandler,
+ ruleSets: RuleSets,
language: Language
) {
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/index/InspectionDataSource.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/index/InspectionDataSource.kt
index 10f95ae78..5ef958463 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/index/InspectionDataSource.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/index/InspectionDataSource.kt
@@ -35,4 +35,8 @@ class InspectionDataSource(private val fileContent: FileContent) : DataSource {
override fun getNiceFileName(shortNames: Boolean, inputFileName: String?): String {
return fileContent.fileName
}
+
+ override fun close() {
+ // empty default implementation
+ }
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AliQuickFix.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AliQuickFix.kt
index ee7acc5c4..57e9ffba8 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AliQuickFix.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AliQuickFix.kt
@@ -19,6 +19,7 @@ import com.intellij.codeInspection.LocalQuickFix
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
+import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
@@ -28,6 +29,7 @@ import com.intellij.psi.PsiIdentifier
import com.intellij.psi.PsiLocalVariable
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiParameter
+import java.lang.reflect.Method
/**
*
@@ -47,7 +49,11 @@ interface AliQuickFix : LocalQuickFix {
companion object {
const val groupName = "Ali QuickFix"
- fun doQuickFix(newIdentifier: String, project: Project, psiIdentifier: PsiIdentifier) {
+ fun doQuickFix(
+ newIdentifier: String,
+ project: Project,
+ psiIdentifier: PsiIdentifier
+ ) {
val offset = psiIdentifier.textOffset
val cannotFix = psiIdentifier.parent !is PsiMember
&& !(psiIdentifier.parent is PsiLocalVariable || psiIdentifier.parent is PsiParameter)
@@ -57,25 +63,43 @@ interface AliQuickFix : LocalQuickFix {
val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return
editor.caretModel.moveToOffset(psiIdentifier.textOffset)
- val anAction = ActionManager.getInstance().getAction("RenameElement")
val psiFile = psiIdentifier.containingFile
+
commitDocumentIfNeeded(psiFile, project)
- val event = AnActionEvent.createFromDataContext("MainMenu", anAction.templatePresentation) {
- when (it) {
- CommonDataKeys.PROJECT.name -> project
- CommonDataKeys.EDITOR.name -> editor
- CommonDataKeys.PSI_FILE.name -> psiFile
- CommonDataKeys.PSI_ELEMENT.name -> psiIdentifier.parent
- else -> null
- }
- }
+
val psiFacade = JavaPsiFacade.getInstance(project)
val factory = psiFacade.elementFactory
- anAction.actionPerformed(event)
+ try {
+ val application = ApplicationManager.getApplication()
+ val isWriteThreadMethod: Method =
+ application.javaClass.getDeclaredMethod("isWriteThread")
+ val isWriteThread = isWriteThreadMethod.invoke(application)
+ if (!(isWriteThread as Boolean)) {
+ val anAction =
+ ActionManager.getInstance().getAction("RenameElement")
+ val event = AnActionEvent.createFromDataContext(
+ "MainMenu",
+ anAction.templatePresentation
+ ) {
+ when (it) {
+ CommonDataKeys.PROJECT.name -> project
+ CommonDataKeys.EDITOR.name -> editor
+ CommonDataKeys.PSI_FILE.name -> psiFile
+ CommonDataKeys.PSI_ELEMENT.name -> psiIdentifier.parent
+ else -> null
+ }
+ }
+ anAction.actionPerformed(event)
+ }
+ } catch (e: Exception) {
+ } finally {
+ }
// origin PsiIdentifier is unavailable
psiFile.findElementAt(offset)?.replace(factory.createIdentifier(newIdentifier))
+
+ commitDocumentIfNeeded(psiFile, project)
}
private fun commitDocumentIfNeeded(file: PsiFile?, project: Project) {
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AvoidStartWithDollarAndUnderLineNamingQuickFix.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AvoidStartWithDollarAndUnderLineNamingQuickFix.kt
index 24e985962..a2c6eb170 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AvoidStartWithDollarAndUnderLineNamingQuickFix.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/AvoidStartWithDollarAndUnderLineNamingQuickFix.kt
@@ -19,7 +19,7 @@ import com.alibaba.p3c.idea.i18n.P3cBundle
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiIdentifier
-import org.apache.commons.lang3.StringUtils
+import org.apache.commons.lang3.RegExUtils
/**
*
@@ -40,7 +40,7 @@ object AvoidStartWithDollarAndUnderLineNamingQuickFix : AliQuickFix {
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val psiIdentifier = descriptor.psiElement as? PsiIdentifier ?: return
val identifier = psiIdentifier.text
- val resultName = StringUtils.replacePattern(identifier, "^[\$_]+", "")
+ val resultName = RegExUtils.replacePattern(identifier, "^[\$_]+", "")
if (resultName.toLongOrNull() != null) {
return
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ClassMustHaveAuthorQuickFix.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ClassMustHaveAuthorQuickFix.kt
index f9fb072ee..b676cac75 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ClassMustHaveAuthorQuickFix.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ClassMustHaveAuthorQuickFix.kt
@@ -33,9 +33,11 @@ object ClassMustHaveAuthorQuickFix : InspectionGadgetsFix(), AliQuickFix {
val tag = "@author ${System.getProperty("user.name") ?: System.getenv("USER")}"
- override fun doFix(project: Project?, descriptor: ProblemDescriptor?) {
+ override fun doFix(project: Project, descriptor: ProblemDescriptor) {
descriptor ?: return
- val psiClass = descriptor.psiElement as? PsiClass ?: descriptor.psiElement?.parent as? PsiClass ?: return
+ val psiClass = descriptor.psiElement as? PsiClass
+ ?: descriptor.psiElement?.parent as? PsiClass
+ ?: return
val document = psiClass.docComment
val psiFacade = JavaPsiFacade.getInstance(project)
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ConstantFieldShouldBeUpperCaseQuickFix.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ConstantFieldShouldBeUpperCaseQuickFix.kt
index 85da4f5ac..e294891a2 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ConstantFieldShouldBeUpperCaseQuickFix.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/ConstantFieldShouldBeUpperCaseQuickFix.kt
@@ -20,6 +20,7 @@ import com.google.common.base.Splitter
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiIdentifier
+import java.util.Locale
/**
*
@@ -28,7 +29,7 @@ import com.intellij.psi.PsiIdentifier
* @date 2017/02/28
*/
object ConstantFieldShouldBeUpperCaseQuickFix : AliQuickFix {
- val separator = '_'
+ const val separator = '_'
override fun getName(): String {
return P3cBundle.getMessage("com.alibaba.p3c.idea.quickfix.field.to.upperCaseWithUnderscore")
@@ -40,7 +41,7 @@ object ConstantFieldShouldBeUpperCaseQuickFix : AliQuickFix {
val list = Splitter.on(separator).trimResults().omitEmptyStrings().splitToList(identifier)
val resultName = list.joinToString(separator.toString()) {
- separateCamelCase(it).toUpperCase()
+ separateCamelCase(it).uppercase()
}
AliQuickFix.doQuickFix(resultName, project, psiIdentifier)
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/DecorateInspectionFix.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/DecorateInspectionFix.kt
index 052bf560a..881aaf61c 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/DecorateInspectionFix.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/DecorateInspectionFix.kt
@@ -15,6 +15,7 @@
*/
package com.alibaba.p3c.idea.quickfix
+import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.siyeh.ig.InspectionGadgetsFix
@@ -25,9 +26,11 @@ import com.siyeh.ig.InspectionGadgetsFix
* @author caikang
* @date 2017/03/02
*/
-class DecorateInspectionGadgetsFix(val fix: InspectionGadgetsFix,
- internal val name: String,
- internal val familyName: String = name) : InspectionGadgetsFix() {
+class DecorateInspectionGadgetsFix(
+ val fix: LocalQuickFix,
+ internal val name: String,
+ internal val familyName: String = name
+) : InspectionGadgetsFix() {
override fun getName(): String {
return name
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/LowerCamelCaseVariableNamingQuickFix.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/LowerCamelCaseVariableNamingQuickFix.kt
index 579025d20..50b79b33f 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/LowerCamelCaseVariableNamingQuickFix.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/LowerCamelCaseVariableNamingQuickFix.kt
@@ -45,11 +45,15 @@ object LowerCamelCaseVariableNamingQuickFix : AliQuickFix {
}
private fun toLowerCamelCase(identifier: String): String {
- val list = Splitter.onPattern("[^a-z0-9A-Z]+").trimResults()
- .omitEmptyStrings().split(identifier).toList()
+ val list = Splitter
+ .onPattern("[^a-z0-9A-Z]+")
+ .trimResults()
+ .omitEmptyStrings()
+ .split(identifier)
+ .toList()
val result = list.mapIndexed { i, s ->
val charArray = s.toCharArray()
- charArray[0] = if (i == 0) charArray[0].toLowerCase() else charArray[0].toUpperCase()
+ charArray[0] = if (i == 0) charArray[0].lowercaseChar() else charArray[0].uppercaseChar()
String(charArray)
}
return result.joinToString("")
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/DocumentUtils.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/DocumentUtils.kt
index 54635e597..c41d86d7a 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/DocumentUtils.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/DocumentUtils.kt
@@ -26,7 +26,7 @@ import com.intellij.openapi.util.TextRange
6
*/
object DocumentUtils {
- private val PMD_TAB_SIZE = 8
+ private const val PMD_TAB_SIZE = 8
fun calculateRealOffset(document: Document, line: Int, pmdColumn: Int): Int {
val maxLine = document.lineCount
if (maxLine < line) {
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightDisplayLevels.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightDisplayLevels.kt
index 4c42da961..e2d791266 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightDisplayLevels.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightDisplayLevels.kt
@@ -27,4 +27,6 @@ object HighlightDisplayLevels {
val BLOCKER = HighlightDisplayLevel(HighlightSeverities.BLOCKER, HighlightDisplayLevel.ERROR.icon)
val CRITICAL = HighlightDisplayLevel(HighlightSeverities.CRITICAL, HighlightDisplayLevel.WARNING.icon)
val MAJOR = HighlightDisplayLevel(HighlightSeverities.MAJOR, HighlightDisplayLevel.WEAK_WARNING.icon)
+ val WARNING = HighlightDisplayLevel(HighlightSeverities.WARNING, HighlightDisplayLevel.WEAK_WARNING.icon)
+ val WEAK_WARNING = HighlightDisplayLevel(HighlightSeverities.WEAK_WARNING, HighlightDisplayLevel.WEAK_WARNING.icon)
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightInfoTypes.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightInfoTypes.kt
index 16504ca8a..cd479ae26 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightInfoTypes.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightInfoTypes.kt
@@ -31,4 +31,8 @@ object HighlightInfoTypes {
CodeInsightColors.WARNINGS_ATTRIBUTES)
val MAJOR: HighlightInfoType = HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverities.MAJOR,
CodeInsightColors.WEAK_WARNING_ATTRIBUTES)
+ val WARNING: HighlightInfoType = HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverities.WARNING,
+ CodeInsightColors.WEAK_WARNING_ATTRIBUTES)
+ val WEAK_WARNING: HighlightInfoType = HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverities.WEAK_WARNING,
+ CodeInsightColors.WEAK_WARNING_ATTRIBUTES)
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightSeverities.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightSeverities.kt
index 5f75753ba..80017e281 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightSeverities.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/HighlightSeverities.kt
@@ -24,16 +24,14 @@ import com.intellij.lang.annotation.HighlightSeverity
* @date 2017/02/04
*/
object HighlightSeverities {
+ val BLOCKER = HighlightSeverity("BLOCKER", 399)
+
+ val CRITICAL = HighlightSeverity("CRITICAL", 398)
+
val MAJOR = HighlightSeverity("MAJOR", 397)
+ val WARNING = HighlightSeverity("WARNING", 396)
- /**
- * The standard severity level for warning annotations.
- */
- val CRITICAL = HighlightSeverity("CRITICAL", 398)
+ val WEAK_WARNING = HighlightSeverity("WEAK_WARNING", 395)
- /**
- * The standard severity level for error annotations.
- */
- val BLOCKER = HighlightSeverity("BLOCKER", 399)
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/NumberConstants.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/NumberConstants.kt
index b71c8db79..1dd8cdc3e 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/NumberConstants.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/NumberConstants.kt
@@ -20,10 +20,10 @@ package com.alibaba.p3c.idea.util
* @date 2016/12/28
*/
object NumberConstants {
- val INTEGER_SIZE_OR_LENGTH_0 = 0
- val INTEGER_SIZE_OR_LENGTH_1 = 1
- val INTEGER_SIZE_OR_LENGTH_2 = 2
+ const val INTEGER_SIZE_OR_LENGTH_0 = 0
+ const val INTEGER_SIZE_OR_LENGTH_1 = 1
+ const val INTEGER_SIZE_OR_LENGTH_2 = 2
- val INDEX_0 = 0
- val INDEX_1 = 1
+ const val INDEX_0 = 0
+ const val INDEX_1 = 1
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ObjectConstants.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ObjectConstants.kt
index b54ea3fcf..c527c2a67 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ObjectConstants.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ObjectConstants.kt
@@ -20,11 +20,11 @@ package com.alibaba.p3c.idea.util
* @date 2016/12/28
*/
object ObjectConstants {
- val METHOD_NAME_EQUALS = "equals"
- val METHOD_NAME_HASHCODE = "hashCode"
- val METHOD_NAME_ADD = "add"
- val METHOD_NAME_PUT = "put"
- val CLASS_LITERAL = "class"
- val INTERFACE_LITERAL = "interface"
- val ENUM_LITERAL = "enum"
+ const val METHOD_NAME_EQUALS = "equals"
+ const val METHOD_NAME_HASHCODE = "hashCode"
+ const val METHOD_NAME_ADD = "add"
+ const val METHOD_NAME_PUT = "put"
+ const val CLASS_LITERAL = "class"
+ const val INTERFACE_LITERAL = "interface"
+ const val ENUM_LITERAL = "enum"
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ProblemsUtils.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ProblemsUtils.kt
index 4c74a1545..6159aefef 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ProblemsUtils.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/ProblemsUtils.kt
@@ -15,7 +15,7 @@
*/
package com.alibaba.p3c.idea.util
-import com.alibaba.p3c.pmd.lang.java.rule.comment.AvoidCommentBehindStatementRule
+import com.xenoamess.p3c.pmd.lang.java.rule.comment.AvoidCommentBehindStatementRule
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
@@ -42,13 +42,21 @@ import com.intellij.psi.impl.source.tree.ElementType
object ProblemsUtils {
private val highlightLineRules = setOf(AvoidCommentBehindStatementRule::class.java.simpleName)
- fun createProblemDescriptorForPmdRule(psiFile: PsiFile, manager: InspectionManager, isOnTheFly: Boolean,
- ruleName: String, desc: String, start: Int, end: Int,
+ fun createProblemDescriptorForPmdRule(
+ psiFile: PsiFile,
+ manager: InspectionManager,
+ isOnTheFly: Boolean,
+ ruleName: String,
+ desc: String,
+ start: Int,
+ end: Int,
checkLine: Int = 0,
quickFix: (PsiElement) -> LocalQuickFix? = {
QuickFixes.getQuickFix(ruleName, isOnTheFly)
- }): ProblemDescriptor? {
- val document = FileDocumentManager.getInstance().getDocument(psiFile.virtualFile) ?: return null
+ }
+ ): ProblemDescriptor? {
+ val document = FileDocumentManager.getInstance().getDocument(psiFile.virtualFile)
+ ?: return null
if (highlightLineRules.contains(ruleName) && checkLine <= document.lineCount) {
val lineNumber = if (start >= document.textLength) {
document.lineCount - 1
@@ -82,9 +90,15 @@ object ProblemsUtils {
}
endElement = psiElement
}
- return manager.createProblemDescriptor(psiElement, endElement,
- desc, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly,
- quickFix(psiElement))
+ val localQuickFix = quickFix(psiElement) ?: return null
+ return manager.createProblemDescriptor(
+ psiElement,
+ endElement,
+ desc,
+ ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
+ isOnTheFly,
+ localQuickFix
+ )
}
private fun getEndElement(psiFile: PsiFile, psiElement: PsiElement, endOffset: Int): PsiElement {
@@ -113,9 +127,14 @@ object ProblemsUtils {
if (psiElement == null) {
return null
}
- if (psiElement is PsiKeyword && psiElement.text != null && (ObjectConstants.CLASS_LITERAL == psiElement.text
- || ObjectConstants.INTERFACE_LITERAL == psiElement.text
- || ObjectConstants.ENUM_LITERAL == psiElement.text) && psiElement.parent is PsiClass) {
+ if (psiElement is PsiKeyword
+ && psiElement.text != null
+ && (ObjectConstants.CLASS_LITERAL == psiElement.text
+ || ObjectConstants.INTERFACE_LITERAL == psiElement.text
+ || ObjectConstants.ENUM_LITERAL == psiElement.text
+ )
+ && psiElement.parent is PsiClass
+ ) {
val parent = psiElement.parent as PsiClass
val identifier = parent.nameIdentifier
return identifier ?: psiElement
@@ -123,14 +142,25 @@ object ProblemsUtils {
return psiElement
}
- private fun createTextRangeProblem(manager: InspectionManager, textRange: TextRange, isOnTheFly: Boolean,
- psiFile: PsiFile, ruleName: String, desc: String,
+ private fun createTextRangeProblem(
+ manager: InspectionManager,
+ textRange: TextRange,
+ isOnTheFly: Boolean,
+ psiFile: PsiFile,
+ ruleName: String,
+ desc: String,
quickFix: () -> LocalQuickFix? = {
QuickFixes.getQuickFix(ruleName, isOnTheFly)
- }): ProblemDescriptor {
-
+ }
+ ): ProblemDescriptor? {
+ val localQuickFix = quickFix();
+ if (localQuickFix == null) {
+ return manager.createProblemDescriptor(psiFile, textRange,
+ desc, ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
+ isOnTheFly)
+ }
return manager.createProblemDescriptor(psiFile, textRange,
desc, ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
- isOnTheFly, quickFix())
+ isOnTheFly, localQuickFix)
}
}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/vcs/AliCodeAnalysisCheckinHandler.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/vcs/AliCodeAnalysisCheckinHandler.kt
index df369b133..97fe31a49 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/vcs/AliCodeAnalysisCheckinHandler.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/vcs/AliCodeAnalysisCheckinHandler.kt
@@ -64,8 +64,8 @@ import javax.swing.JPanel
* @date 2017/05/04
*/
class AliCodeAnalysisCheckinHandler(
- private val myProject: Project,
- private val myCheckinPanel: CheckinProjectPanel
+ private val myProject: Project,
+ private val myCheckinPanel: CheckinProjectPanel
) : CheckinHandler() {
private val dialogTitle = "Alibaba Code Analyze"
private val cancelText = "&Cancel"
@@ -107,18 +107,22 @@ class AliCodeAnalysisCheckinHandler(
}
override fun beforeCheckin(
- executor: CommitExecutor?,
- additionalDataConsumer: PairConsumer
+ executor: CommitExecutor?,
+ additionalDataConsumer: PairConsumer
): CheckinHandler.ReturnResult {
if (!getSettings().analysisBeforeCheckin) {
return CheckinHandler.ReturnResult.COMMIT
}
if (DumbService.getInstance(myProject).isDumb) {
if (Messages.showOkCancelDialog(
- myProject,
- "Code analysis is impossible until indices are up-to-date", dialogTitle,
- waitingText, commitText, null
- ) == Messages.OK
+ myProject,
+ "Code analysis is impossible until indices are up-to-date",
+ dialogTitle,
+ waitingText,
+ commitText,
+ null
+ )
+ == Messages.OK
) {
return CheckinHandler.ReturnResult.CANCEL
}
@@ -135,9 +139,14 @@ class AliCodeAnalysisCheckinHandler(
return CheckinHandler.ReturnResult.COMMIT
}
if (Messages.showOkCancelDialog(
- myProject, "Found suspicious code,continue commit?",
- dialogTitle, commitText, cancelText, null
- ) == Messages.OK
+ myProject,
+ "Found suspicious code,continue commit?",
+ dialogTitle,
+ commitText,
+ cancelText,
+ null
+ )
+ == Messages.OK
) {
return CheckinHandler.ReturnResult.COMMIT
} else {
@@ -149,8 +158,8 @@ class AliCodeAnalysisCheckinHandler(
fun doAnalysis(project: Project, virtualFiles: Array) {
val managerEx = InspectionManager.getInstance(project) as InspectionManagerEx
val analysisScope = AnalysisScope(
- project,
- ArrayList(Arrays.asList(*virtualFiles))
+ project,
+ ArrayList(listOf(*virtualFiles))
)
val tools = Inspections.aliInspections(project) { it.tool is AliBaseInspection }
AliInspectionAction.createContext(tools, managerEx, null, false, analysisScope)
@@ -161,7 +170,7 @@ class AliCodeAnalysisCheckinHandler(
ApplicationManager.getApplication().assertIsDispatchThread()
PsiDocumentManager.getInstance(myProject).commitAllDocuments()
if (ApplicationManager.getApplication().isWriteAccessAllowed) throw RuntimeException(
- "Must not run under write action"
+ "Must not run under write action"
)
val result = AtomicBoolean(false)
val exception = Ref.create()
@@ -173,9 +182,11 @@ class AliCodeAnalysisCheckinHandler(
val inspectionManager = InspectionManager.getInstance(project)
val psiManager = PsiManager.getInstance(project)
val count = AtomicInteger(0)
- val hasViolation = virtualFiles.asSequence().any { file ->
+ val hasViolation = virtualFiles.asSequence().any {
+ file ->
ApplicationManager.getApplication().runReadAction(Computable {
- val psiFile = psiManager.findFile(file) ?: return@Computable false
+ val psiFile = psiManager.findFile(file)
+ ?: return@Computable false
val curCount = count.incrementAndGet()
progress.text = file.canonicalPath
progress.fraction = curCount.toDouble() / virtualFiles.size.toDouble()
diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/P3cMutex.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/activity/AliBaseApplicationStartupActivity.kt
similarity index 64%
rename from eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/P3cMutex.kt
rename to idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/activity/AliBaseApplicationStartupActivity.kt
index 8dab560a6..13825f868 100644
--- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/P3cMutex.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/activity/AliBaseApplicationStartupActivity.kt
@@ -13,22 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.alibaba.smartfox.eclipse.job
+package com.alibaba.smartfox.idea.common.activity
-import org.eclipse.core.runtime.jobs.ISchedulingRule
+import com.intellij.openapi.startup.StartupActivity
/**
*
*
* @author caikang
- * @date 2017/06/14
+ * @date 2017/05/11
*/
-object P3cMutex : ISchedulingRule {
- override fun contains(rule: ISchedulingRule?): Boolean {
- return isConflicting(rule)
- }
-
- override fun isConflicting(rule: ISchedulingRule?): Boolean {
- return rule == this
- }
-}
\ No newline at end of file
+interface AliBaseApplicationStartupActivity : StartupActivity
\ No newline at end of file
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/BalloonNotifications.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/BalloonNotifications.kt
index 6963bbbba..bf96657e9 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/BalloonNotifications.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/BalloonNotifications.kt
@@ -23,6 +23,7 @@ import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.Messages
+import org.apache.http.MethodNotSupportedException
import java.awt.Component
import java.net.UnknownHostException
@@ -33,12 +34,12 @@ import java.net.UnknownHostException
* @date 2017/05/08
*/
object BalloonNotifications {
- val displayId = "SmartFox Intellij IDEA Balloon Notification"
- val balloonGroup = NotificationGroup(displayId, NotificationDisplayType.BALLOON, true)
+ const val displayId = "SmartFox Intellij IDEA Balloon Notification"
+ val balloonGroup = buildNotificationGroup(displayId, NotificationDisplayType.BALLOON, true)
- val stickyBalloonDisplayId = "SmartFox Intellij IDEA Notification"
- val stickyBalloonGroup = NotificationGroup(stickyBalloonDisplayId, NotificationDisplayType.STICKY_BALLOON, true)
- val TITLE = "SmartFox Intellij IDEA Plugin"
+ const val stickyBalloonDisplayId = "SmartFox Intellij IDEA Notification"
+ val stickyBalloonGroup = buildNotificationGroup(stickyBalloonDisplayId, NotificationDisplayType.STICKY_BALLOON, true)
+ const val TITLE = "SmartFox Intellij IDEA Plugin"
fun showInfoDialog(component: Component, title: String, message: String) {
Messages.showInfoMessage(component, message, title)
@@ -56,29 +57,29 @@ object BalloonNotifications {
}
fun showSuccessNotification(message: String, project: Project? = ProjectManager.getInstance().defaultProject,
- title: String = TITLE, sticky: Boolean = false) {
+ title: String = TITLE, sticky: Boolean = false) {
showNotification(message, project, title, NotificationType.INFORMATION, null, sticky)
}
fun showWarnNotification(message: String, project: Project? = ProjectManager.getInstance().defaultProject,
- title: String = TITLE, sticky: Boolean = false) {
+ title: String = TITLE, sticky: Boolean = false) {
showNotification(message, project, title, NotificationType.WARNING, null, sticky)
}
fun showErrorNotification(message: String, project: Project? = ProjectManager.getInstance().defaultProject,
- title: String = TITLE, sticky: Boolean = false) {
+ title: String = TITLE, sticky: Boolean = false) {
showNotification(message, project, title, NotificationType.ERROR, null, sticky)
}
fun showSuccessNotification(message: String, project: Project?,
- notificationListener: NotificationListener, title: String = TITLE, sticky: Boolean = false) {
+ notificationListener: NotificationListener, title: String = TITLE, sticky: Boolean = false) {
showNotification(message, project, title, NotificationType.INFORMATION, notificationListener, sticky)
}
fun showNotification(message: String, project: Project? = ProjectManager.getInstance().defaultProject,
- title: String = TITLE,
- notificationType: NotificationType = NotificationType.INFORMATION,
- notificationListener: NotificationListener? = null, sticky: Boolean = false) {
+ title: String = TITLE,
+ notificationType: NotificationType = NotificationType.INFORMATION,
+ notificationListener: NotificationListener? = null, sticky: Boolean = false) {
val group = if (sticky) {
stickyBalloonGroup
} else {
@@ -100,7 +101,8 @@ object BalloonNotifications {
}
object LogNotifications {
- val group = NotificationGroup(BalloonNotifications.displayId, NotificationDisplayType.NONE, true)
+
+ val group = buildNotificationGroup(displayId = BalloonNotifications.displayId, displayType = NotificationDisplayType.NONE, isLogByDefault = true)
fun log(message: String, project: Project? = ProjectManager.getInstance().defaultProject,
title: String = BalloonNotifications.TITLE,
@@ -109,3 +111,19 @@ object LogNotifications {
group.createNotification(title, message, notificationType, notificationListener).notify(project)
}
}
+
+
+fun buildNotificationGroup(displayId: String, displayType: NotificationDisplayType, isLogByDefault: Boolean): NotificationGroup {
+ val notificationGroupClass = Class.forName("com.intellij.notification.NotificationGroup")
+ notificationGroupClass.constructors.forEach {
+ if (it.parameters.size == 3) {
+ try {
+ return it.newInstance(displayId, displayType, isLogByDefault)
+ as NotificationGroup
+ } catch (e: Exception) {
+ System.err.println(e)
+ }
+ }
+ }
+ throw MethodNotSupportedException("cannot find a suitable constructor for NotificationGroup who accepts [String,NotificationDisplayType,Boolean]")
+}
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/CommonExtensions.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/CommonExtensions.kt
index 7b77198fd..3aecc2cbd 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/CommonExtensions.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/CommonExtensions.kt
@@ -15,7 +15,7 @@
*/
package com.alibaba.smartfox.idea.common.util
-import com.intellij.openapi.components.ServiceManager
+import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
/**
@@ -25,9 +25,9 @@ import com.intellij.openapi.project.Project
* @date 2017/06/19
*/
fun Class.getService(): T {
- return ServiceManager.getService(this)
+ return ApplicationManager.getApplication().getService(this)
}
fun Class.getService(project: Project): T {
- return ServiceManager.getService(project, this)
+ return project.getService(this)
}
\ No newline at end of file
diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/PluginVersions.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/PluginVersions.kt
index 993c04013..99b65ae06 100644
--- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/PluginVersions.kt
+++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/PluginVersions.kt
@@ -17,6 +17,7 @@ package com.alibaba.smartfox.idea.common.util
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManager
+import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.cl.PluginClassLoader
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.extensions.PluginId
@@ -25,15 +26,15 @@ import com.intellij.openapi.extensions.PluginId
* @author caikang
*/
object PluginVersions {
- val baseVersion141 = 141
- val baseVersion143 = 143
- val baseVersion145 = 145
- val baseVersion162 = 162
- val baseVersion163 = 163
- val baseVersion171 = 171
+ const val baseVersion141 = 141
+ const val baseVersion143 = 143
+ const val baseVersion145 = 145
+ const val baseVersion162 = 162
+ const val baseVersion163 = 163
+ const val baseVersion171 = 171
val pluginId: PluginId = (javaClass.classLoader as PluginClassLoader).pluginId
- val pluginDescriptor: IdeaPluginDescriptor = PluginManager.getPlugin(pluginId)!!
+ val pluginDescriptor: IdeaPluginDescriptor = PluginManagerCore.getPlugin(pluginId)!!
/**
* 获取当前安装的 plugin版本
diff --git a/idea-plugin/p3c-common/src/main/resources/messages/P3cBundle.xml b/idea-plugin/p3c-common/src/main/resources/messages/P3cBundle.xml
index 438ba9469..1792436f3 100644
--- a/idea-plugin/p3c-common/src/main/resources/messages/P3cBundle.xml
+++ b/idea-plugin/p3c-common/src/main/resources/messages/P3cBundle.xml
@@ -4,8 +4,7 @@
阿里编码规约
切换语言至英文(English)
切换语言至中文
-
- 重启后生效]]>
+ 重启后生效]]>
编码规约扫描
关闭实时检测功能
打开实时检测功能
@@ -15,48 +14,28 @@
修改为小写驼峰命名(lowerCamelCase)
为变量添加!
替换为
- 通过类 '%s' 直接访问静态成员
- '%s.%s'
-
+ 通过类 '%s' 直接访问静态成员 '%s.%s'
添加 @Override 注解
为语句加上大括号
翻转 equals 调用
修改为 String[] str 模式
'l' 替换为 'L'
-
- #ref #loc]]>
-
- 避免通过一个类的对象引用访问此类的静态变量或静态方法,无谓增加编译器解析成本,直接用类名来访问即可。
-
- 不应该通过类实例访问静态成员
- %s #loc
-
+ #ref #loc]]>
+ 避免通过一个类的对象引用访问此类的静态变量或静态方法,无谓增加编译器解析成本,直接用类名来访问即可。
+ 不应该通过类实例访问静态成员 %s #loc
不能使用过时的类或方法。
-
- 所有的覆写方法,必须加@Override注解。
-
-
- #ref()缺少 '@Override' 注解 #loc]]>
-
- Map/Set的key为自定义对象时,必须重写hashCode和equals。
-
-
- 参数类型 %s 没有重写hashCode和equals #loc
-
-
- #ref 是非线程安全的,请加锁或者使用局部变量 #loc]]>
-
- #ref 没有加大括号 #loc]]>
-
- #ref 应该作为方法 "%s()"的调用方,而不是参数 #loc]]>
-
- #ref 数组定义格式错误 #loc]]>
-
- #ref 应该以大写L结尾 #loc]]>
-
- #ref #loc]]>
+ 所有的覆写方法,必须加@Override注解。
+ #ref()缺少 '@Override' 注解 #loc]]>
+ Map/Set的key为自定义对象时,必须重写hashCode和equals。
+ 参数类型 %s 没有重写hashCode和equals #loc
+ #ref 是非线程安全的,请加锁或者使用局部变量 #loc]]>
+ #ref 没有加大括号 #loc]]>
+ #ref 应该作为方法 "%s()"的调用方,而不是参数 #loc]]>
+ #ref 数组定义格式错误 #loc]]>
+ #ref 应该以大写L结尾 #loc]]>
+ #ref #loc]]>
@@ -81,8 +60,7 @@