sonar-checkstyle plugin源码
生活随笔
收集整理的這篇文章主要介紹了
sonar-checkstyle plugin源码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
sonar-checkstyle plugin 與 sonar-findbugs plugin 差不多,代碼目錄也幾乎很相近。
sonar 插件需要擴展sensor,Exporter,Plugin,Importer類:
CheckstyleSensor 類:
CheckstylePlugin 繼承sonarPlugin類:
public final class CheckstylePluginextends SonarPlugin {private static final String CHECKSTYLE_SUB_CATEGORY_NAME = "Checkstyle";public List getExtensions(){return Arrays.asList(new Object[] {PropertyDefinition.builder("sonar.checkstyle.filters").defaultValue("<module name=\"SuppressionCommentFilter\" /><module name=\"SuppressWarningsFilter\" />").category("java").subCategory("Checkstyle").name("Filters").description("Checkstyle supports four error filtering mechanisms: <code>SuppressionCommentFilter</code>, <code>SuppressWithNearbyCommentFilter</code>, <code>SuppressionFilter</code>, and <code>SuppressWarningsFilter</code>.This property allows the configuration of those filters with a native XML format. See the <a href='http://checkstyle.sourceforge.net/config.html'>Checkstyle</a> configuration for more information.").type(PropertyType.TEXT).onQualifiers("TRK", new String[] { "BRC" }).build(), PropertyDefinition.builder("sonar.checkstyle.generateXml").defaultValue("false").category("java").subCategory("Checkstyle").name("Generate XML Report").type(PropertyType.BOOLEAN).hidden().build(), CheckstyleSensor.class, CheckstyleConfiguration.class, CheckstyleExecutor.class, CheckstyleAuditListener.class, CheckstyleProfileExporter.class, CheckstyleProfileImporter.class, CheckstyleRulesDefinition.class });} }CheckstyleProfileExporter 繼承ProfileExporter
public class CheckstyleProfileExporterextends ProfileExporter {public static final String DOCTYPE_DECLARATION = "<!DOCTYPE module PUBLIC \"-//Puppy Crawl//DTD Check Configuration 1.2//EN\" \"http://www.puppycrawl.com/dtds/configuration_1_2.dtd\">";private static final String CLOSE_MODULE = "</module>";private final Settings settings;public CheckstyleProfileExporter(Settings settings){super("checkstyle", "Checkstyle");this.settings = settings;setSupportedLanguages(new String[] { "java" });setMimeType("application/xml");}public void exportProfile(RulesProfile profile, Writer writer){try{List<ActiveRule> activeRules = profile.getActiveRulesByRepository("checkstyle");if (activeRules != null){Map<String, List<ActiveRule>> activeRulesByConfigKey = arrangeByConfigKey(activeRules);generateXml(writer, activeRulesByConfigKey);}}catch (IOException ex){throw new IllegalStateException("Fail to export the profile " + profile, ex);}}private void generateXml(Writer writer, Map<String, List<ActiveRule>> activeRulesByConfigKey)throws IOException{appendXmlHeader(writer);appendCustomFilters(writer);appendCheckerModules(writer, activeRulesByConfigKey);appendTreeWalker(writer, activeRulesByConfigKey);appendXmlFooter(writer);}private static void appendXmlHeader(Writer writer)throws IOException{writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE module PUBLIC \"-//Puppy Crawl//DTD Check Configuration 1.2//EN\" \"http://www.puppycrawl.com/dtds/configuration_1_2.dtd\"><!-- Generated by Sonar --><module name=\"Checker\">");}private void appendCustomFilters(Writer writer)throws IOException{String filtersXml = this.settings.getString("sonar.checkstyle.filters");if (StringUtils.isNotBlank(filtersXml)) {writer.append(filtersXml);}}private static void appendCheckerModules(Writer writer, Map<String, List<ActiveRule>> activeRulesByConfigKey)throws IOException{for (Map.Entry<String, List<ActiveRule>> entry : activeRulesByConfigKey.entrySet()){String configKey = (String)entry.getKey();if (!isInTreeWalker(configKey)){List<ActiveRule> activeRules = (List)entry.getValue();for (ActiveRule activeRule : activeRules) {appendModule(writer, activeRule);}}}}private void appendTreeWalker(Writer writer, Map<String, List<ActiveRule>> activeRulesByConfigKey)throws IOException{writer.append("<module name=\"TreeWalker\">");writer.append("<module name=\"FileContentsHolder\"/> ");if (isSuppressWarningsEnabled()) {writer.append("<module name=\"SuppressWarningsHolder\"/> ");}List<String> ruleSet = new ArrayList(activeRulesByConfigKey.keySet());Collections.sort(ruleSet);for (String configKey : ruleSet) {if (isInTreeWalker(configKey)){List<ActiveRule> activeRules = (List)activeRulesByConfigKey.get(configKey);for (ActiveRule activeRule : activeRules) {appendModule(writer, activeRule);}}}writer.append("</module>");}private boolean isSuppressWarningsEnabled(){String filtersXml = this.settings.getString("sonar.checkstyle.filters");boolean result = false;if (filtersXml != null) {result = filtersXml.contains("<module name=\"SuppressWarningsFilter\" />");}return result;}private static void appendXmlFooter(Writer writer)throws IOException{writer.append("</module>");}@VisibleForTestingstatic boolean isInTreeWalker(String configKey){return StringUtils.startsWithIgnoreCase(configKey, "Checker/TreeWalker/");}private static Map<String, List<ActiveRule>> arrangeByConfigKey(List<ActiveRule> activeRules){Map<String, List<ActiveRule>> result = new HashMap();for (ActiveRule activeRule : activeRules){String key = activeRule.getConfigKey();if (result.containsKey(key)){List<ActiveRule> rules = (List)result.get(key);rules.add(activeRule);}else{List<ActiveRule> rules = new ArrayList();rules.add(activeRule);result.put(key, rules);}}return result;}private static void appendModule(Writer writer, ActiveRule activeRule)throws IOException{String moduleName = StringUtils.substringAfterLast(activeRule.getConfigKey(), "/");writer.append("<module name=\"");StringEscapeUtils.escapeXml(writer, moduleName);writer.append("\">");if (activeRule.getRule().getTemplate() != null) {appendModuleProperty(writer, "id", activeRule.getRuleKey());}appendModuleProperty(writer, "severity", CheckstyleSeverityUtils.toSeverity(activeRule.getSeverity()));appendRuleParameters(writer, activeRule);writer.append("</module>");}private static void appendRuleParameters(Writer writer, ActiveRule activeRule)throws IOException{for (RuleParam ruleParam : activeRule.getRule().getParams()){String value = activeRule.getParameter(ruleParam.getKey());if (StringUtils.isNotBlank(value)) {appendModuleProperty(writer, ruleParam.getKey(), value);}}}private static void appendModuleProperty(Writer writer, String propertyKey, String propertyValue)throws IOException{if (StringUtils.isNotBlank(propertyValue)){writer.append("<property name=\"");StringEscapeUtils.escapeXml(writer, propertyKey);writer.append("\" value=\"");StringEscapeUtils.escapeXml(writer, propertyValue);writer.append("\"/>");}} }CheckstyleProfileImporter 繼承ProfileImporter,checkstyle 是針對java語言的規則提供者
public class CheckstyleProfileImporterextends ProfileImporter {private static final Logger LOG = LoggerFactory.getLogger(CheckstyleProfileImporter.class);private static final String CHECKER_MODULE = "Checker";private static final String TREEWALKER_MODULE = "TreeWalker";private static final String MODULE_NODE = "module";private static final String[] FILTERS = { "SeverityMatchFilter", "SuppressionFilter", "SuppressWarningsFilter", "SuppressionCommentFilter", "SuppressWithNearbyCommentFilter" };private final RuleFinder ruleFinder;public CheckstyleProfileImporter(RuleFinder ruleFinder){super("checkstyle", "Checkstyle");setSupportedLanguages(new String[] { "java" });this.ruleFinder = ruleFinder;}private Module loadModule(SMInputCursor parentCursor)throws XMLStreamException{Module result = new Module(null);result.name = parentCursor.getAttrValue("name");SMInputCursor cursor = parentCursor.childElementCursor();while (cursor.getNext() != null){String nodeName = cursor.getLocalName();if ("module".equals(nodeName)){result.modules.add(loadModule(cursor));}else if ("property".equals(nodeName)){String key = cursor.getAttrValue("name");String value = cursor.getAttrValue("value");result.properties.put(key, value);}}return result;}public RulesProfile importProfile(Reader reader, ValidationMessages messages){SMInputFactory inputFactory = initStax();RulesProfile profile = RulesProfile.create();try{checkerModule = loadModule(inputFactory.rootElementCursor(reader).advance());for (Module rootModule : checkerModule.modules){Map<String, String> rootModuleProperties = new HashMap(checkerModule.properties);rootModuleProperties.putAll(rootModule.properties);if (StringUtils.equals("TreeWalker", rootModule.name)) {processTreewalker(profile, rootModule, rootModuleProperties, messages);} else {processModule(profile, "Checker/", rootModule.name, rootModuleProperties, messages);}}}catch (XMLStreamException ex){Module checkerModule;String message = "XML is not valid: " + ex.getMessage();LOG.error(message, ex);messages.addErrorText(message);}return profile;}private void processTreewalker(RulesProfile profile, Module rootModule, Map<String, String> rootModuleProperties, ValidationMessages messages){for (Module treewalkerModule : rootModule.modules){Map<String, String> treewalkerModuleProperties = new HashMap(rootModuleProperties);treewalkerModuleProperties.putAll(treewalkerModule.properties);processModule(profile, "Checker/TreeWalker/", treewalkerModule.name, treewalkerModuleProperties, messages);}}private static SMInputFactory initStax(){XMLInputFactory xmlFactory = XMLInputFactory.newInstance();xmlFactory.setProperty("javax.xml.stream.isCoalescing", Boolean.TRUE);xmlFactory.setProperty("javax.xml.stream.isNamespaceAware", Boolean.FALSE);xmlFactory.setProperty("javax.xml.stream.supportDTD", Boolean.FALSE);xmlFactory.setProperty("javax.xml.stream.isValidating", Boolean.FALSE);return new SMInputFactory(xmlFactory);}private void processModule(RulesProfile profile, String path, String moduleName, Map<String, String> properties, ValidationMessages messages){if (isFilter(moduleName)) {messages.addWarningText("Checkstyle filters are not imported: " + moduleName);} else if (!isIgnored(moduleName)) {processRule(profile, path, moduleName, properties, messages);}}@VisibleForTestingstatic boolean isIgnored(String configKey){return (StringUtils.equals(configKey, "FileContentsHolder")) || (StringUtils.equals(configKey, "SuppressWarningsHolder"));}@VisibleForTestingstatic boolean isFilter(String configKey){boolean result = false;for (String filter : FILTERS) {if (StringUtils.equals(configKey, filter)){result = true;break;}}return result;}private void processRule(RulesProfile profile, String path, String moduleName, Map<String, String> properties, ValidationMessages messages){String id = (String)properties.get("id");String warning;Rule rule;String warning;if (StringUtils.isNotBlank(id)){Rule rule = this.ruleFinder.find(RuleQuery.create().withRepositoryKey("checkstyle").withKey(id));warning = "Checkstyle rule with key '" + id + "' not found";}else{String configKey = path + moduleName;rule = this.ruleFinder.find(RuleQuery.create().withRepositoryKey("checkstyle").withConfigKey(configKey));warning = "Checkstyle rule with config key '" + configKey + "' not found";}if (rule == null){messages.addWarningText(warning);}else{ActiveRule activeRule = profile.activateRule(rule, null);activateProperties(activeRule, properties);}}private static void activateProperties(ActiveRule activeRule, Map<String, String> properties){for (Map.Entry<String, String> property : properties.entrySet()) {if (StringUtils.equals("severity", (String)property.getKey())) {activeRule.setSeverity(CheckstyleSeverityUtils.fromSeverity((String)property.getValue()));} else if (!StringUtils.equals("id", (String)property.getKey())) {activeRule.setParameter((String)property.getKey(), (String)property.getValue());}}}private static class Module{private final Map<String, String> properties = new HashMap();private final List<Module> modules = new ArrayList();private String name;} }對于sonar plugin 如果要具有導出規則的能力,需要聲明一個類繼承BatchExtension,類BatchExtension來自于sonar-api包
package org.sonar.plugins.checkstyle;import com.google.common.annotations.VisibleForTesting; import com.puppycrawl.tools.checkstyle.Checker; import com.puppycrawl.tools.checkstyle.PackageNamesLoader; import com.puppycrawl.tools.checkstyle.XMLLogger; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.BatchExtension; import org.sonar.api.utils.TimeProfiler; import org.sonar.plugins.java.api.JavaResourceLocator;public class CheckstyleExecutorimplements BatchExtension {public static final String PROPERTIES_PATH = "/org/sonar/plugins/checkstyle/checkstyle-plugin.properties";private static final Logger LOG = LoggerFactory.getLogger(CheckstyleExecutor.class);private final CheckstyleConfiguration configuration;private final CheckstyleAuditListener listener;private final JavaResourceLocator javaResourceLocator;public CheckstyleExecutor(CheckstyleConfiguration configuration, CheckstyleAuditListener listener, JavaResourceLocator javaResourceLocator){this.configuration = configuration;this.listener = listener;this.javaResourceLocator = javaResourceLocator;}public void execute(){Locale initialLocale = Locale.getDefault();Locale.setDefault(Locale.ENGLISH);ClassLoader initialClassLoader = Thread.currentThread().getContextClassLoader();Thread.currentThread().setContextClassLoader(PackageNamesLoader.class.getClassLoader());URLClassLoader projectClassloader = createClassloader();try{executeWithClassLoader(projectClassloader);}finally{Thread.currentThread().setContextClassLoader(initialClassLoader);Locale.setDefault(initialLocale);close(projectClassloader);}}private void executeWithClassLoader(URLClassLoader projectClassloader){TimeProfiler profiler = new TimeProfiler().start("Execute Checkstyle " + new CheckstyleVersion().getVersion("/org/sonar/plugins/checkstyle/checkstyle-plugin.properties"));Checker checker = new Checker();OutputStream xmlOutput = null;try{checker.setClassLoader(projectClassloader);checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());checker.addListener(this.listener);File xmlReport = this.configuration.getTargetXmlReport();if (xmlReport != null){LOG.info("Checkstyle output report: {}", xmlReport.getAbsolutePath());xmlOutput = FileUtils.openOutputStream(xmlReport);checker.addListener(new XMLLogger(xmlOutput, true));}checker.setCharset(this.configuration.getCharset().name());checker.configure(this.configuration.getCheckstyleConfiguration());checker.process(this.configuration.getSourceFiles());profiler.stop();}catch (Exception ex){throw new IllegalStateException("Can not execute Checkstyle", ex);}finally{checker.destroy();if (xmlOutput != null) {close(xmlOutput);}}}@VisibleForTestingstatic void close(Closeable closeable){try{closeable.close();}catch (IOException ex){throw new IllegalStateException("failed to close object", ex);}}@VisibleForTestingURL getUrl(URI uri){try{return uri.toURL();}catch (MalformedURLException ex){throw new IllegalStateException("Fail to create the project classloader. Classpath element is invalid: " + uri, ex);}}private URLClassLoader createClassloader(){Collection<File> classpathElements = this.javaResourceLocator.classpath();List<URL> urls = new ArrayList(classpathElements.size());for (File file : classpathElements) {urls.add(getUrl(file.toURI()));}return new URLClassLoader((URL[])urls.toArray(new URL[urls.size()]), null);} }CheckstyleConfiguration implements BatchExtension類:
// checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2017 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USApackage org.sonar.plugins.checkstyle;import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Properties;import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.BatchExtension; import org.sonar.api.batch.fs.FilePredicates; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.config.Settings; import org.sonar.api.profiles.RulesProfile;import com.google.common.annotations.VisibleForTesting; import com.puppycrawl.tools.checkstyle.ConfigurationLoader; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.PropertiesExpander; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration;public class CheckstyleConfiguration implements BatchExtension {public static final String PROPERTY_GENERATE_XML = "sonar.checkstyle.generateXml";private static final Logger LOG = LoggerFactory.getLogger(CheckstyleConfiguration.class);private final CheckstyleProfileExporter confExporter;private final RulesProfile profile;private final Settings conf;private final FileSystem fileSystem;public CheckstyleConfiguration(Settings conf, CheckstyleProfileExporter confExporter,RulesProfile profile, FileSystem fileSystem) {this.conf = conf;this.confExporter = confExporter;this.profile = profile;this.fileSystem = fileSystem;}public File getXmlDefinitionFile() {final File xmlFile = new File(fileSystem.workDir(), "checkstyle.xml");try (Writer writer = new OutputStreamWriter(new FileOutputStream(xmlFile, false),StandardCharsets.UTF_8)) {confExporter.exportProfile(profile, writer);writer.flush();return xmlFile;}catch (IOException ex) {throw new IllegalStateException("Fail to save the Checkstyle configuration to "+ xmlFile.getPath(), ex);}}public List<File> getSourceFiles() {final FilePredicates predicates = fileSystem.predicates();final Iterable<File> files = fileSystem.files(predicates.and(predicates.hasLanguage(CheckstyleConstants.JAVA_KEY),predicates.hasType(InputFile.Type.MAIN)));final List<File> fileList = new ArrayList<>();for (File file : files) {fileList.add(file);}return fileList;}public File getTargetXmlReport() {File result = null;if (conf.getBoolean(PROPERTY_GENERATE_XML)) {result = new File(fileSystem.workDir(), "checkstyle-result.xml");}return result;}public Configuration getCheckstyleConfiguration() throws CheckstyleException {final File xmlConfig = getXmlDefinitionFile();LOG.info("Checkstyle configuration: {}", xmlConfig.getAbsolutePath());final Configuration configuration = toCheckstyleConfiguration(xmlConfig);defineCharset(configuration);return configuration;}@VisibleForTestingstatic Configuration toCheckstyleConfiguration(File xmlConfig) throws CheckstyleException {return ConfigurationLoader.loadConfiguration(xmlConfig.getAbsolutePath(),new PropertiesExpander(new Properties()));}private void defineCharset(Configuration configuration) {defineModuleCharset(configuration);for (Configuration module : configuration.getChildren()) {defineModuleCharset(module);}}private void defineModuleCharset(Configuration module) {if (module instanceof DefaultConfiguration&& ("Checker".equals(module.getName())|| "com.puppycrawl.tools.checkstyle.Checker".equals(module.getName()))) {final Charset charset = getCharset();final String charsetName = charset.name();LOG.info("Checkstyle charset: {}", charsetName);((DefaultConfiguration) module).addAttribute("charset", charsetName);}}public Charset getCharset() {return fileSystem.encoding();}}checkstyle 中依賴的jar包:
pom中依賴的jar包,其中是sonar-api包:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.github.checkstyle</groupId><artifactId>checkstyle-sonar-plugin-parent</artifactId><version>4.0</version></parent><artifactId>checkstyle-sonar-plugin</artifactId><packaging>sonar-plugin</packaging><name>Checkstyle SonarQube Plugin</name><description>Checkstyle is a code analyser to help programmers write Java code that adheres to a coding standard.</description><properties><maven.checkstyle.plugin.version>2.17</maven.checkstyle.plugin.version><maven.sevntu.checkstyle.plugin.version>1.25.0</maven.sevntu.checkstyle.plugin.version></properties><dependencies><dependency><groupId>org.sonarsource.sonarqube</groupId><artifactId>sonar-plugin-api</artifactId><scope>provided</scope><version>${sonar.version}</version></dependency><!-- till https://github.com/checkstyle/sonar-checkstyle/issues/40 --><dependency><groupId>org.sonarsource.java</groupId><artifactId>sonar-java-plugin</artifactId><type>sonar-plugin</type><version>${sonar-java.version}</version><scope>provided</scope><!-- to avoid 4.5.1 api pickup --><exclusions><exclusion><groupId>org.codehaus.sonar</groupId><artifactId>sonar-plugin-api</artifactId></exclusion></exclusions></dependency><!-- required to load external descriptiona, see CheckstyleRulesDefinition --><dependency><groupId>org.sonarsource.sslr-squid-bridge</groupId><artifactId>sslr-squid-bridge</artifactId><version>2.6.1</version><!-- to avoid 4.5.1 api pickup --><exclusions><exclusion><groupId>org.codehaus.sonar</groupId><artifactId>sonar-plugin-api</artifactId></exclusion><exclusion><groupId>org.codehaus.sonar</groupId><artifactId>sonar-colorizer</artifactId></exclusion></exclusions></dependency><dependency><!-- required during runtime, by sonar 5.6.4 --><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.5</version></dependency><dependency><!-- required during runtime, by sonar 5.6.4 --><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>${project.groupId}</groupId><artifactId>checkstyle-all</artifactId><version>${project.version}</version><classifier>shaded</classifier><exclusions><exclusion><!-- we exclude checkstyle as we use shaded version of it --><groupId>com.puppycrawl.tools</groupId><artifactId>checkstyle</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.sonarsource.sonarqube</groupId><artifactId>sonar-plugin-api</artifactId><version>${sonar.version}</version><type>test-jar</type><scope>test</scope></dependency><dependency><groupId>xmlunit</groupId><artifactId>xmlunit</artifactId><scope>test</scope><version>1.4</version></dependency><!--We need following dependency, otherwise we will receivejava.lang.NoClassDefFoundError: org/apache/maven/project/MavenProjectduring call mock(org.sonar.api.resources.Project.class)--><dependency><groupId>org.apache.maven</groupId><artifactId>maven-project</artifactId><version>2.0.7</version><scope>test</scope></dependency><dependency><groupId>org.sonarsource.sonarqube</groupId><artifactId>sonar-testing-harness</artifactId><scope>test</scope><version>${sonar.version}</version></dependency><dependency><groupId>org.easytesting</groupId><artifactId>fest-assert</artifactId><scope>test</scope><version>1.4</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-nop</artifactId><!-- 1.5.6(old) version is requied due to sonar 5.6.4 dependency tree --><version>1.5.6</version><scope>test</scope></dependency><dependency><groupId>org.apache.ant</groupId><artifactId>ant</artifactId><version>1.9.7</version><scope>test</scope></dependency></dependencies><build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering><includes><include>**/checkstyle-plugin.properties</include></includes></resource><resource><directory>src/main/resources</directory><filtering>false</filtering><excludes><exclude>**/checkstyle-plugin.properties</exclude></excludes></resource></resources><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-checkstyle-plugin</artifactId><version>${maven.checkstyle.plugin.version}</version><dependencies><dependency><groupId>com.puppycrawl.tools</groupId><artifactId>checkstyle</artifactId><version>${checkstyle.version}</version></dependency><dependency><groupId>com.github.sevntu-checkstyle</groupId><artifactId>sevntu-checkstyle-maven-plugin</artifactId><version>${maven.sevntu.checkstyle.plugin.version}</version></dependency></dependencies><executions><execution><id>checkstyle-check</id><phase>verify</phase><goals><goal>check</goal></goals><configuration><configLocation>https://raw.githubusercontent.com/checkstyle/checkstyle/checkstyle-${checkstyle.version}/config/checkstyle_checks.xml</configLocation><failOnViolation>true</failOnViolation><headerLocation>I just need to put here smth to let it not use default - LICENSE.txt</headerLocation><propertiesLocation>config/checkstyle.properties</propertiesLocation><sourceDirectory>${project.basedir}/src</sourceDirectory><includeTestResources>false</includeTestResources></configuration></execution><execution><id>sevntu-checkstyle-check</id><phase>verify</phase><goals><goal>check</goal></goals><configuration><configLocation>https://raw.githubusercontent.com/checkstyle/checkstyle/checkstyle-${checkstyle.version}/config/checkstyle_sevntu_checks.xml</configLocation><failOnViolation>true</failOnViolation><includeResources>false</includeResources><includeTestResources>false</includeTestResources><logViolationsToConsole>true</logViolationsToConsole><maxAllowedViolations>0</maxAllowedViolations><violationSeverity>error</violationSeverity><propertyExpansion>project.basedir=${project.basedir}</propertyExpansion><sourceDirectory>${project.basedir}/src</sourceDirectory></configuration></execution></executions></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-pmd-plugin</artifactId><version>3.7</version><configuration><targetJdk>${java.version}</targetJdk><minimumTokens>20</minimumTokens><skipEmptyReport>false</skipEmptyReport><failOnViolation>true</failOnViolation><printFailingErrors>true</printFailingErrors><linkXRef>false</linkXRef><includeTests>true</includeTests><rulesets><ruleset>config/pmd.xml</ruleset></rulesets></configuration><executions><execution><goals><goal>check</goal></goals></execution></executions></plugin><plugin><groupId>org.codehaus.mojo</groupId><artifactId>findbugs-maven-plugin</artifactId><version>3.0.4</version><configuration><effort>Max</effort><threshold>Low</threshold><excludeFilterFile>config/findbugs-exclude.xml</excludeFilterFile></configuration><executions><execution><goals><goal>check</goal></goals></execution></executions></plugin><plugin><groupId>de.thetaphi</groupId><artifactId>forbiddenapis</artifactId><version>2.2</version><configuration><targetVersion>${java.version}</targetVersion><failOnUnsupportedJava>false</failOnUnsupportedJava><bundledSignatures><bundledSignature>jdk-unsafe</bundledSignature><bundledSignature>jdk-deprecated</bundledSignature><bundledSignature>jdk-system-out</bundledSignature><bundledSignature>jdk-non-portable</bundledSignature></bundledSignatures></configuration><executions><execution><goals><goal>check</goal><goal>testCheck</goal></goals></execution></executions></plugin><plugin><groupId>org.codehaus.mojo</groupId><artifactId>cobertura-maven-plugin</artifactId><version>2.7</version><configuration><!--<quiet>true</quiet>--><formats><format>xml</format><format>html</format></formats><check><haltOnFailure>true</haltOnFailure><branchRate>100</branchRate><lineRate>100</lineRate><totalBranchRate>82</totalBranchRate><totalLineRate>96</totalLineRate><regexes><regex><pattern>org.sonar.plugins.checkstyle.CheckstyleAuditListener</pattern><branchRate>71</branchRate><lineRate>86</lineRate></regex><regex><pattern>org.sonar.plugins.checkstyle.CheckstyleConfiguration</pattern><branchRate>60</branchRate><lineRate>93</lineRate></regex><regex><pattern>org.sonar.plugins.checkstyle.CheckstyleProfileExporter</pattern><branchRate>87</branchRate><lineRate>97</lineRate></regex><regex><pattern>org.sonar.plugins.checkstyle.CheckstyleProfileImporter</pattern><branchRate>97</branchRate><lineRate>100</lineRate></regex><regex><pattern>org.sonar.plugins.checkstyle.CheckstyleRulesDefinition</pattern><branchRate>50</branchRate><lineRate>90</lineRate></regex><regex><pattern>org.sonar.plugins.checkstyle.CheckstyleSensor</pattern><branchRate>100</branchRate><lineRate>87</lineRate></regex><regex><pattern>org.sonar.plugins.checkstyle.CheckstyleSeverityUtils</pattern><branchRate>75</branchRate><lineRate>96</lineRate></regex></regexes></check></configuration><executions><execution><goals><goal>check</goal></goals></execution></executions></plugin><plugin><groupId>edu.illinois</groupId><artifactId>nondex-maven-plugin</artifactId><version>1.1.1</version></plugin><plugin><groupId>org.sonarsource.sonar-packaging-maven-plugin</groupId><artifactId>sonar-packaging-maven-plugin</artifactId><version>1.17</version><extensions>true</extensions><configuration><pluginKey>checkstyle</pluginKey><pluginName>Checkstyle</pluginName><pluginClass>org.sonar.plugins.checkstyle.CheckstylePlugin</pluginClass><pluginDescription><![CDATA[Analyze Java code with <a href="http://checkstyle.sourceforge.net/">Checkstyle</a>.]]></pluginDescription><archive><manifestEntries><!-- ${buildNumber} is the svn revision generated by the buildnumber-maven-plugin --><Implementation-Build>${buildNumber}</Implementation-Build><Build-Time>${timestamp}</Build-Time></manifestEntries></archive></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-enforcer-plugin</artifactId><version>1.4.1</version><executions><execution><id>enforce-plugin-size</id><goals><goal>enforce</goal></goals><phase>verify</phase><configuration><rules><requireFilesSize><maxsize>10000000</maxsize><minsize>5000000</minsize><files><file>${project.build.directory}/${project.build.finalName}.jar</file></files></requireFilesSize></rules></configuration></execution></executions></plugin></plugins></build><pluginRepositories><pluginRepository><id>sevntu-maven</id><name>sevntu-maven</name><url>http://sevntu-checkstyle.github.io/sevntu.checkstyle/maven2</url></pluginRepository></pluginRepositories></project>總結
以上是生活随笔為你收集整理的sonar-checkstyle plugin源码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpaceX已经成功 我国征集空间站商业
- 下一篇: 浪潮信息发布 KOS 服务器操作系统:基