Foreign norms acclimatized? Taught how you expand Ali norms idea plugins

Original: little sister the taste (micro-channel public number ID: xjjdog), please share, reproduced Please keep the source.

Many companies are norms java development Alibaba. This article will briefly talk about the need to regulate, and introduce two underlying principles. Finally, I taught you how to develop Java extensions Alibaba protocol plug: P3C, add your custom rules.

This Heart pay attention to internal strength training , ordinary people need to practice for three months , and get through the re putting master, three hours to Make.

Renduermai open conditions were as follows:

1. 熟悉maven
2. 熟悉gradle
3. 熟悉pmd
4. 经常抓网站(熟悉xpath)
5. 会写java代码
复制代码

First, why should a custom specification

Who is to maintain the code? Is gitlab? Or jdk? After all, these apes or procedural humans to maintain!

First, the code is posters, and followed to the machine. No one can understand, no one can maintain that the code is a residue (¯_, ¯)

So, the question is , how to write anyone see understand the code?
A: System - set - Regulation - Fan!

Then, the problem again , although each company has its own coding standards, but often out to finish the work, laziness, mood & personal level & habits and other factors, coupled with no Review , the final code is daunting.

With no one to comply with norms, how to enforce it?
A: AC - to - work - with! (Hey - look at this pot thrown arc developed a lot like tears?)

This paper describes the java static code checking tool PMD, Alibaba p3c open source project, so that you learn how to develop their own code of chic specification, the liberation of your hands, and preaching endless.

Second, the basic principle

The ancients said, a gentleman born non-different too, good fake to things. Will mean big brother is leveraging can skillfully deflected the question. Now introduce the jack under the current period.

1.PMD static code scanning

Outline

PMD (Project Manager Design) is an open source Java code analysis tool error, error code that it learned through static analysis. That report errors without running Java programs. Which itself comes with many rules can be used directly, use these rules can identify many of the problems of Java source code.

E.g:

Potential bug: empty if / try / catch / finally / switch statements
unused code: Local unused variables, parameters, and other private methods
optional code: String / StringBuffer abuse
complex expressions: not necessary if statement, you can use a while loop to complete the loop for
repeated code: paste the code == paste bug
loop to create a new object: to create objects temporarily cool, has always been to create a cool
resource Off: after Connect, Result, statement and other use to ensure close

In addition, users can define their own rules, checks Java code meets certain coding standards. For example, you can write a rule requiring PMD find all create Thread and Socket objects.

Headquarters: pmd.github.io/

working principle

PMD is the core JavaCC parser generator. Which combined with the use JavaCC and EBNF (Extended Backus - Naur Form, Extended Backus-Naur Formal) grammar, plus JJTree, the Java source code analysis into an abstract syntax tree (AST, Abstract Syntax Tree)

From the fundamental point of view, Java source code, just plain text. However, in order to make that plain text is legitimate Java code, they must meet certain structural requirements.

Syntactic metalanguage such a structure may be called EBNF and is commonly referred to as "grammar" (Grammar). JavaCC generated parser according to the syntax requirements, can be used to parse this parser program written in the Java programming language.

Classification rules

Best Practice: Rules recognized best practices.
pmd.github.io/pmd-6.4.0/p...

Code Style: These rules are enforced specific coding style.
( Pmd.github.io/pmd-6.4.0/p... )

Design: helps you discover the rules of design problems.
( Pmd.github.io/pmd-6.4.0/p... )

Documentation: The documentation for the rules and codes.
( Pmd.github.io/pmd-6.4.0/p... )

Error-prone rule: for detecting damaged, very confusing or erroneous configuration rules prone runtime.
( Pmd.github.io/pmd-6.4.0/p... )

Multithreading: The rules mark issues when dealing with multiple threads of execution.
( Pmd.github.io/pmd-6.4.0/p... )

Performance: mark code rules exist performance problems.
( Pmd.github.io/pmd-6.4.0/p... )

Security: display rules potential safety defects.
( Pmd.github.io/pmd-6.4.0/p... )

2. Ali Baba Java development protocol plug p3c

p3c mainly includes three parts:

pmd-P3C , most of the rules to achieve, based on the development of PMD, if you want to implement their own rules, based on this module development (based on maven compiler package)

plugin-IDEA , IntelliJ IDEA plugin (based gradle compiler package)

Headquarters: github.com/alibaba/p3c

Third, how do?

Having said that, that in the end how to write custom extensions p3c rules? (͡ ° ͜ʖ ͡ °)

Custom design rules

The usual spring-mvc example.

Assumptions need to develop a rule: @RequestMapping comment on the method need to specify method parameters. [Otherwise swagger generate documentation can give birth to a bunch of gourd doll]

//前方swagger葫芦娃预警
@RequestMapping("/hehe")
public String sayHeHe() {
    return "hehe";
}
//仅GET、POST方法
@RequestMapping(value = "/hehe",method = {RequestMethod.GET,RequestMethod.POST})
public String sayHeHe() {
    return "hehe";
}
复制代码

Preparation Phase

Download PMD ( pmd.github.io/ )

Pull P3C Code ( github.com/alibaba/p3c )

A cup of coffee (o≖◡≖)

PMD graphical tools

Decompression PMD, open /pmd-bin-6.17.0/bin/designer.bat

Use graphical tools to build the syntax tree, ferret out problems in your code

Related code is as follows

package com.test.rest.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
    @RequestMapping(value="/hehe",method = {RequestMethod.GET,RequestMethod.POST})
    public String sayHeHe() {
        return "hehe";
    }
    @RequestMapping("/heihei")
    public String sayHeiHei() {
        return "heihei";
    }
    @RequestMapping(value="/haha")
    public String sayHaHa() {
        return "haha";
    }
}
复制代码

Analysis syntax tree

Can be seen that the whole tree is the root of a CompilationUnit, i.e. coding unit, java representing each source file.

@RequestMapping we must first find the location, click on the appropriate nodes to see if the cursor position to source the method declaration.

Careful analysis ClassOrInterfaceBody, found Annotation node, this is what we need to start with the place

Note that due to the different wording, is divided into a NormalAnnotation and SingleMemberAnnotation, for subsequent processing XPath can write

//ClassOrInterfaceBody//Annotation[@AnnotationName='RequestMapping']
复制代码

To verify what the expression is correct, it will throw PMD graphical interface XPATH Expression box

Write p3c-pmd

Open p3c-pmd engineering, start writing custom rules.

Ali has written many of the rules, the rules we now belongs to write object-oriented category, the rules can be written under oop package.

Create a rule class RequestMappingRule, inherited from AbstractAliRule, visit rewrite method:

The relevant code

public class RequestMappingRule extends AbstractAliRule {
    private static final String IMPORT_XPATH = "//ImportDeclaration[@ImportedName='org.springframework.web.bind.annotation.RequestMapping']";
    private static final String REQUESTMAPPING_XPATH = "//ClassOrInterfaceBody//Annotation[@AnnotationName='RequestMapping']";
    private static final String METHOD_XPATH = "MemberValuePairs/MemberValuePair[@MemberName='method']";
    @Override
    public Object visit(ASTCompilationUnit node, Object data) {
        try {
            List<Node> importNodes = node.findChildNodesWithXPath(IMPORT_XPATH);
            if (null != importNodes && importNodes.size() > 0) {
                List<Node> resquestMappingNodes = node.findChildNodesWithXPath(REQUESTMAPPING_XPATH);
                Node annotation = null;
                for (Node resquestMappingNode:resquestMappingNodes) {
                    annotation = resquestMappingNode.jjtGetChild(0);
                    if(annotation instanceof ASTSingleMemberAnnotation){
                        addViolationWithMessage(data, resquestMappingNode, "java.oop.RequestMappingRule.rule.msg", new Object[]{});
                    }else if(annotation instanceof ASTNormalAnnotation){
                        if(!annotation.hasDescendantMatchingXPath(METHOD_XPATH)){
                            addViolationWithMessage(data, resquestMappingNode, "java.oop.RequestMappingRule.rule.msg", new Object[]{});
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
        return super.visit(node, data);
    }
}
复制代码

Rules Configuration

The write good rule configuration file to ali-oop.xml

The relevant code

<rule name="RequestMappingRule"
          language="java"
          message="java.oop.RequestMappingRule.rule.msg"
          class="com.alibaba.p3c.pmd.lang.java.rule.oop.RequestMappingRule">
        <description>java.oop.StringConcatRule.rule.msg.desc</description>
        <!--级别,1强制,2推荐,3参考-->
        <priority>2</priority>
        <example>
            <![CDATA[
        Negative example:
            @RequestMapping("/heihei")
            @RequestMapping(value="/haha")
        ]]>
        </example>
        <example>
            <![CDATA[
        Positive example:
            @RequestMapping(value="/hehe",method = {RequestMethod.GET,RequestMethod.POST})
        ]]>
        </example>
    </rule>
复制代码

Rules prompt written information

The two-step tips and rules need to write information used to message.xml profile, message_en.xml for English prompts, elective

unit test

Preparation of test samples, will be tested source code written to the xml file directory corresponding to the test

The relevant code

<?xml version="1.0" encoding="UTF-8"?>
<test-data xmlns="http://pmd.sourceforge.net/rule-tests"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://pmd.sourceforge.net/rule-tests https://pmd.sourceforge.io/rule-tests_1_0_0.xsd">
    <code-fragment id="RequestMapping-use">
        <![CDATA[
package com.test.rest.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
    @RequestMapping(value="/hehe",method = {RequestMethod.GET,RequestMethod.POST})
    public String sayHeHe() {
        return "hehe";
    }
    @RequestMapping("/heihei")
    public String sayHeiHei() {
        return "heihei";
    }
    @RequestMapping(value="/haha")
    public String sayHaHa() {
        return "haha";
    }
}
        ]]>
    </code-fragment>
    <test-code>
        <description>RequestMapping use rule</description>
        <expected-problems>0</expected-problems>
        <expected-linenumbers>21,27</expected-linenumbers>
        <code-ref id="RequestMapping-use"/>
    </test-code>
</test-data>
复制代码

Write unit tests

Running unit tests, because the sample code 21, 27 line does not meet specifications, but we expect the number of written questions is zero, so the unit will not pass the test:

p3c-pmd packaging

The p3c-pmd installed to your local maven repository

First without plug-ins maven-javadoc-pluginand maven-gpg-plugincomment out, then run mvn command:

mvn -DskipTests=true clean install
复制代码

Plug-idea-plugin package

idea-plugin-based project gradle build, deploy build.gradle the root directory, so use a local private maven build warehouse building

And then run to start building gradle:

cd p3c-idea
gradle clean buildPlugin
复制代码

After a successful package will idea-plugin\p3c-idea\build\distributions\generate a directory Alibaba Java Coding Guidelines-1.0.0.zipfile, this is our own expanding Ali joined the development of the Statute of plug-ins.

After installation effect IDEA follows:

End

I'm lazy, too lazy to focus on some issues such as the coding of fine quality. But I want to write some beautiful code, at least follow the norms of the code. With a tool that saves a lot of effort, after the small partners experience, but also address him easy to use.

These are the things I thankfully, I also let go of power lazy.

About the Author: little sister the taste (xjjdog), does not allow the public a number of detours programmer. Focus infrastructure and Linux. Decade architecture, day ten billion flow, and you explore the world of high concurrency, give you a different taste. My personal micro-channel xjjdog0, welcome to add friends, further exchanges.

Guess you like

Origin juejin.im/post/5d6c7beb6fb9a06b244334e2