View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.plugins.pmd;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.lang.reflect.InvocationTargetException;
24  import java.lang.reflect.Method;
25  import java.nio.file.Path;
26  import java.util.ArrayList;
27  import java.util.Collection;
28  import java.util.Collections;
29  import java.util.HashMap;
30  import java.util.HashSet;
31  import java.util.LinkedHashSet;
32  import java.util.LinkedList;
33  import java.util.List;
34  import java.util.Map;
35  import java.util.Set;
36  import java.util.TreeMap;
37  
38  import net.sourceforge.pmd.PMDVersion;
39  import org.apache.maven.execution.MavenSession;
40  import org.apache.maven.model.ReportPlugin;
41  import org.apache.maven.model.Reporting;
42  import org.apache.maven.plugins.annotations.Component;
43  import org.apache.maven.plugins.annotations.Parameter;
44  import org.apache.maven.project.MavenProject;
45  import org.apache.maven.reporting.AbstractMavenReport;
46  import org.apache.maven.reporting.MavenReportException;
47  import org.apache.maven.toolchain.Toolchain;
48  import org.apache.maven.toolchain.ToolchainManager;
49  import org.codehaus.plexus.util.FileUtils;
50  import org.codehaus.plexus.util.PathTool;
51  import org.codehaus.plexus.util.StringUtils;
52  
53  /**
54   * Base class for the PMD reports.
55   *
56   * @author <a href="mailto:brett@apache.org">Brett Porter</a>
57   * @version $Id$
58   */
59  public abstract class AbstractPmdReport extends AbstractMavenReport {
60      // ----------------------------------------------------------------------
61      // Configurables
62      // ----------------------------------------------------------------------
63  
64      /**
65       * The output directory for the intermediate XML report.
66       */
67      @Parameter(property = "project.build.directory", required = true)
68      protected File targetDirectory;
69  
70      /**
71       * Set the output format type, in addition to the HTML report. Must be one of: "none", "csv", "xml", "txt" or the
72       * full class name of the PMD renderer to use. See the net.sourceforge.pmd.renderers package javadoc for available
73       * renderers. XML is produced in any case, since this format is needed
74       * for the check goals (pmd:check, pmd:aggregator-check, pmd:cpd-check, pmd:aggregator-cpd-check).
75       */
76      @Parameter(property = "format", defaultValue = "xml")
77      protected String format = "xml";
78  
79      /**
80       * Link the violation line numbers to the source xref. Links will be created automatically if the jxr plugin is
81       * being used.
82       */
83      @Parameter(property = "linkXRef", defaultValue = "true")
84      private boolean linkXRef;
85  
86      /**
87       * Location of the Xrefs to link to.
88       */
89      @Parameter(defaultValue = "${project.reporting.outputDirectory}/xref")
90      private File xrefLocation;
91  
92      /**
93       * Location of the Test Xrefs to link to.
94       */
95      @Parameter(defaultValue = "${project.reporting.outputDirectory}/xref-test")
96      private File xrefTestLocation;
97  
98      /**
99       * A list of files to exclude from checking. Can contain Ant-style wildcards and double wildcards. Note that these
100      * exclusion patterns only operate on the path of a source file relative to its source root directory. In other
101      * words, files are excluded based on their package and/or class name. If you want to exclude entire source root
102      * directories, use the parameter <code>excludeRoots</code> instead.
103      *
104      * @since 2.2
105      */
106     @Parameter
107     private List<String> excludes;
108 
109     /**
110      * A list of files to include from checking. Can contain Ant-style wildcards and double wildcards. Defaults to
111      * **\/*.java.
112      *
113      * @since 2.2
114      */
115     @Parameter
116     private List<String> includes;
117 
118     /**
119      * Specifies the location of the source directories to be used for PMD.
120      * Defaults to <code>project.compileSourceRoots</code>.
121      * @since 3.7
122      */
123     @Parameter(defaultValue = "${project.compileSourceRoots}")
124     private List<String> compileSourceRoots;
125 
126     /**
127      * The directories containing the test-sources to be used for PMD.
128      * Defaults to <code>project.testCompileSourceRoots</code>
129      * @since 3.7
130      */
131     @Parameter(defaultValue = "${project.testCompileSourceRoots}")
132     private List<String> testSourceRoots;
133 
134     /**
135      * The project source directories that should be excluded.
136      *
137      * @since 2.2
138      */
139     @Parameter
140     private File[] excludeRoots;
141 
142     /**
143      * Run PMD on the tests.
144      *
145      * @since 2.2
146      */
147     @Parameter(defaultValue = "false")
148     protected boolean includeTests;
149 
150     /**
151      * Whether to build an aggregated report at the root, or build individual reports.
152      *
153      * @since 2.2
154      * @deprecated since 3.15.0 Use the goals <code>pmd:aggregate-pmd</code> and <code>pmd:aggregate-cpd</code>
155      * instead.
156      */
157     @Parameter(property = "aggregate", defaultValue = "false")
158     @Deprecated
159     protected boolean aggregate;
160 
161     /**
162      * Whether to include the xml files generated by PMD/CPD in the site.
163      *
164      * @since 3.0
165      */
166     @Parameter(defaultValue = "false")
167     protected boolean includeXmlInSite;
168 
169     /**
170      * Skip the PMD/CPD report generation if there are no violations or duplications found. Defaults to
171      * <code>false</code>.
172      *
173      * <p>Note: the default value was changed from <code>true</code> to <code>false</code> with version 3.13.0.
174      *
175      * @since 3.1
176      */
177     @Parameter(defaultValue = "false")
178     protected boolean skipEmptyReport;
179 
180     /**
181      * File that lists classes and rules to be excluded from failures.
182      * For PMD, this is a properties file. For CPD, this
183      * is a text file that contains comma-separated lists of classes
184      * that are allowed to duplicate.
185      *
186      * @since 3.7
187      */
188     @Parameter(property = "pmd.excludeFromFailureFile", defaultValue = "")
189     protected String excludeFromFailureFile;
190 
191     /**
192      * Redirect PMD log into maven log out.
193      * When enabled, the PMD log output is redirected to maven, so that
194      * it is visible in the console together with all the other log output.
195      * Also, if maven is started with the debug flag (<code>-X</code> or <code>--debug</code>),
196      * the PMD logger is also configured for debug.
197      *
198      * @since 3.9.0
199      * @deprecated With 3.22.0 and the upgrade to PMD 7, this parameter has no effect anymore. The PMD log
200      * is now always redirected into the maven log and this can't be disabled by this parameter anymore.
201      * In order to disable the logging, see <a href="https://maven.apache.org/maven-logging.html">Maven Logging</a>.
202      * You'd need to start maven with <code>MAVEN_OPTS=-Dorg.slf4j.simpleLogger.log.net.sourceforge.pmd=off mvn &lt;goals&gt;</code>.
203      */
204     @Parameter(defaultValue = "true", property = "pmd.showPmdLog")
205     @Deprecated // (since = "3.22.0", forRemoval = true)
206     protected boolean showPmdLog = true;
207 
208     /**
209      * Used to avoid showing the deprecation warning for "showPmdLog" multiple times.
210      */
211     private boolean warnedAboutShowPmdLog = false;
212 
213     /**
214      * <p>
215      * Allow for configuration of the jvm used to run PMD via maven toolchains.
216      * This permits a configuration where the project is built with one jvm and PMD is executed with another.
217      * This overrules the toolchain selected by the maven-toolchain-plugin.
218      * </p>
219      *
220      * <p>Examples:</p>
221      * (see <a href="https://maven.apache.org/guides/mini/guide-using-toolchains.html">
222      *     Guide to Toolchains</a> for more info)
223      *
224      * <pre>
225      * {@code
226      *    <configuration>
227      *        ...
228      *        <jdkToolchain>
229      *            <version>1.11</version>
230      *        </jdkToolchain>
231      *    </configuration>
232      *
233      *    <configuration>
234      *        ...
235      *        <jdkToolchain>
236      *            <version>1.8</version>
237      *            <vendor>zulu</vendor>
238      *        </jdkToolchain>
239      *    </configuration>
240      *    }
241      * </pre>
242      *
243      * <strong>note:</strong> requires at least Maven 3.3.1
244      *
245      * @since 3.14.0
246      */
247     @Parameter
248     private Map<String, String> jdkToolchain;
249 
250     // ----------------------------------------------------------------------
251     // Read-only parameters
252     // ----------------------------------------------------------------------
253 
254     /**
255      * The projects in the reactor for aggregation report.
256      */
257     @Parameter(property = "reactorProjects", readonly = true)
258     protected List<MavenProject> reactorProjects;
259 
260     /**
261      * The current build session instance. This is used for
262      * toolchain manager API calls and for dependency resolver API calls.
263      */
264     @Parameter(defaultValue = "${session}", required = true, readonly = true)
265     protected MavenSession session;
266 
267     @Component
268     private ToolchainManager toolchainManager;
269 
270     /** The files that are being analyzed. */
271     protected Map<File, PmdFileInfo> filesToProcess;
272 
273     @Override
274     protected MavenProject getProject() {
275         return project;
276     }
277 
278     protected String constructXRefLocation(boolean test) {
279         String location = null;
280         if (linkXRef) {
281             File xrefLoc = test ? xrefTestLocation : xrefLocation;
282 
283             String relativePath =
284                     PathTool.getRelativePath(getReportOutputDirectory().getAbsolutePath(), xrefLoc.getAbsolutePath());
285             if (relativePath == null || relativePath.isEmpty()) {
286                 relativePath = ".";
287             }
288             relativePath = relativePath + "/" + xrefLoc.getName();
289             if (xrefLoc.exists()) {
290                 // XRef was already generated by manual execution of a lifecycle binding
291                 location = relativePath;
292             } else {
293                 // Not yet generated - check if the report is on its way
294                 Reporting reporting = project.getModel().getReporting();
295                 List<ReportPlugin> reportPlugins =
296                         reporting != null ? reporting.getPlugins() : Collections.<ReportPlugin>emptyList();
297                 for (ReportPlugin plugin : reportPlugins) {
298                     String artifactId = plugin.getArtifactId();
299                     if ("maven-jxr-plugin".equals(artifactId) || "jxr-maven-plugin".equals(artifactId)) {
300                         location = relativePath;
301                     }
302                 }
303             }
304 
305             if (location == null) {
306                 getLog().warn("Unable to locate Source XRef to link to - DISABLED");
307             }
308         }
309         return location;
310     }
311 
312     /**
313      * Convenience method to get the list of files where the PMD tool will be executed
314      *
315      * @return a List of the files where the PMD tool will be executed
316      * @throws IOException If an I/O error occurs during construction of the
317      *                     canonical pathnames of the files
318      */
319     protected Map<File, PmdFileInfo> getFilesToProcess() throws IOException {
320         if (aggregate && !project.isExecutionRoot()) {
321             return Collections.emptyMap();
322         }
323 
324         if (excludeRoots == null) {
325             excludeRoots = new File[0];
326         }
327 
328         Collection<File> excludeRootFiles = new HashSet<>(excludeRoots.length);
329 
330         for (File file : excludeRoots) {
331             if (file.isDirectory()) {
332                 excludeRootFiles.add(file);
333             }
334         }
335 
336         List<PmdFileInfo> directories = new ArrayList<>();
337 
338         if (null == compileSourceRoots) {
339             compileSourceRoots = project.getCompileSourceRoots();
340         }
341         if (compileSourceRoots != null) {
342             for (String root : compileSourceRoots) {
343                 File sroot = new File(root);
344                 if (sroot.exists()) {
345                     String sourceXref = constructXRefLocation(false);
346                     directories.add(new PmdFileInfo(project, sroot, sourceXref));
347                 }
348             }
349         }
350 
351         if (null == testSourceRoots) {
352             testSourceRoots = project.getTestCompileSourceRoots();
353         }
354         if (includeTests && testSourceRoots != null) {
355             for (String root : testSourceRoots) {
356                 File sroot = new File(root);
357                 if (sroot.exists()) {
358                     String testXref = constructXRefLocation(true);
359                     directories.add(new PmdFileInfo(project, sroot, testXref));
360                 }
361             }
362         }
363         if (isAggregator()) {
364             for (MavenProject localProject : getAggregatedProjects()) {
365                 List<String> localCompileSourceRoots = localProject.getCompileSourceRoots();
366                 for (String root : localCompileSourceRoots) {
367                     File sroot = new File(root);
368                     if (sroot.exists()) {
369                         String sourceXref = constructXRefLocation(false);
370                         directories.add(new PmdFileInfo(localProject, sroot, sourceXref));
371                     }
372                 }
373                 if (includeTests) {
374                     List<String> localTestCompileSourceRoots = localProject.getTestCompileSourceRoots();
375                     for (String root : localTestCompileSourceRoots) {
376                         File sroot = new File(root);
377                         if (sroot.exists()) {
378                             String testXref = constructXRefLocation(true);
379                             directories.add(new PmdFileInfo(localProject, sroot, testXref));
380                         }
381                     }
382                 }
383             }
384         }
385 
386         String excluding = getExcludes();
387         getLog().debug("Exclusions: " + excluding);
388         String including = getIncludes();
389         getLog().debug("Inclusions: " + including);
390 
391         Map<File, PmdFileInfo> files = new TreeMap<>();
392 
393         for (PmdFileInfo finfo : directories) {
394             getLog().debug("Searching for files in directory "
395                     + finfo.getSourceDirectory().toString());
396             File sourceDirectory = finfo.getSourceDirectory();
397             if (sourceDirectory.isDirectory() && !isDirectoryExcluded(excludeRootFiles, sourceDirectory)) {
398                 List<File> newfiles = FileUtils.getFiles(sourceDirectory, including, excluding);
399                 for (File newfile : newfiles) {
400                     files.put(newfile.getCanonicalFile(), finfo);
401                 }
402             }
403         }
404 
405         return files;
406     }
407 
408     private boolean isDirectoryExcluded(Collection<File> excludeRootFiles, File sourceDirectoryToCheck) {
409         boolean returnVal = false;
410         for (File excludeDir : excludeRootFiles) {
411             try {
412                 if (sourceDirectoryToCheck
413                         .getCanonicalFile()
414                         .toPath()
415                         .startsWith(excludeDir.getCanonicalFile().toPath())) {
416                     getLog().debug("Directory " + sourceDirectoryToCheck.getAbsolutePath()
417                             + " has been excluded as it matches excludeRoot "
418                             + excludeDir.getAbsolutePath());
419                     returnVal = true;
420                     break;
421                 }
422             } catch (IOException e) {
423                 getLog().warn("Error while checking " + sourceDirectoryToCheck + " whether it should be excluded.", e);
424             }
425         }
426         return returnVal;
427     }
428 
429     /**
430      * Gets the comma separated list of effective include patterns.
431      *
432      * @return The comma separated list of effective include patterns, never <code>null</code>.
433      */
434     private String getIncludes() {
435         Collection<String> patterns = new LinkedHashSet<>();
436         if (includes != null) {
437             patterns.addAll(includes);
438         }
439         if (patterns.isEmpty()) {
440             patterns.add("**/*.java");
441         }
442         return StringUtils.join(patterns.iterator(), ",");
443     }
444 
445     /**
446      * Gets the comma separated list of effective exclude patterns.
447      *
448      * @return The comma separated list of effective exclude patterns, never <code>null</code>.
449      */
450     private String getExcludes() {
451         Collection<String> patterns = new LinkedHashSet<>(FileUtils.getDefaultExcludesAsList());
452         if (excludes != null) {
453             patterns.addAll(excludes);
454         }
455         return StringUtils.join(patterns.iterator(), ",");
456     }
457 
458     protected boolean isXml() {
459         return "xml".equals(format);
460     }
461 
462     /**
463      * {@inheritDoc}
464      */
465     @Override
466     public boolean canGenerateReport() {
467         if (!showPmdLog && !warnedAboutShowPmdLog) {
468             getLog().warn("The parameter \"showPmdLog\" has been deprecated and will be removed."
469                     + "Setting it to \"false\" has no effect.");
470             warnedAboutShowPmdLog = true;
471         }
472 
473         if (aggregate && !project.isExecutionRoot()) {
474             return false;
475         }
476 
477         if (!isAggregator() && "pom".equalsIgnoreCase(project.getPackaging())) {
478             return false;
479         }
480 
481         // if format is XML, we need to output it even if the file list is empty
482         // so the "check" goals can check for failures
483         if (isXml()) {
484             return true;
485         }
486         try {
487             filesToProcess = getFilesToProcess();
488             if (filesToProcess.isEmpty()) {
489                 return false;
490             }
491         } catch (IOException e) {
492             getLog().error(e);
493         }
494         return true;
495     }
496 
497     protected String determineCurrentRootLogLevel() {
498         String logLevel = System.getProperty("org.slf4j.simpleLogger.defaultLogLevel");
499         if (logLevel == null) {
500             logLevel = System.getProperty("maven.logging.root.level");
501         }
502         if (logLevel == null) {
503             // TODO: logback level
504             logLevel = "info";
505         }
506         return logLevel;
507     }
508 
509     static String getPmdVersion() {
510         return PMDVersion.VERSION;
511     }
512 
513     // TODO remove the part with ToolchainManager lookup once we depend on
514     // 3.0.9 (have it as prerequisite). Define as regular component field then.
515     protected final Toolchain getToolchain() {
516         Toolchain tc = null;
517 
518         if (jdkToolchain != null) {
519             // Maven 3.3.1 has plugin execution scoped Toolchain Support
520             try {
521                 Method getToolchainsMethod = toolchainManager
522                         .getClass()
523                         .getMethod("getToolchains", MavenSession.class, String.class, Map.class);
524 
525                 @SuppressWarnings("unchecked")
526                 List<Toolchain> tcs =
527                         (List<Toolchain>) getToolchainsMethod.invoke(toolchainManager, session, "jdk", jdkToolchain);
528 
529                 if (tcs != null && !tcs.isEmpty()) {
530                     tc = tcs.get(0);
531                 }
532             } catch (NoSuchMethodException
533                     | SecurityException
534                     | IllegalAccessException
535                     | IllegalArgumentException
536                     | InvocationTargetException e) {
537                 // ignore
538             }
539         }
540 
541         if (tc == null) {
542             tc = toolchainManager.getToolchainFromBuildContext("jdk", session);
543         }
544 
545         return tc;
546     }
547 
548     protected boolean isAggregator() {
549         // returning here aggregate for backwards compatibility
550         return aggregate;
551     }
552 
553     // Note: same logic as in m-javadoc-p (MJAVADOC-134)
554     protected Collection<MavenProject> getAggregatedProjects() {
555         Map<Path, MavenProject> reactorProjectsMap = new HashMap<>();
556         for (MavenProject reactorProject : this.reactorProjects) {
557             reactorProjectsMap.put(reactorProject.getBasedir().toPath(), reactorProject);
558         }
559 
560         return modulesForAggregatedProject(project, reactorProjectsMap);
561     }
562 
563     /**
564      * Recursively add the modules of the aggregatedProject to the set of aggregatedModules.
565      *
566      * @param aggregatedProject the project being aggregated
567      * @param reactorProjectsMap map of (still) available reactor projects
568      * @throws MavenReportException if any
569      */
570     private Set<MavenProject> modulesForAggregatedProject(
571             MavenProject aggregatedProject, Map<Path, MavenProject> reactorProjectsMap) {
572         // Maven does not supply an easy way to get the projects representing
573         // the modules of a project. So we will get the paths to the base
574         // directories of the modules from the project and compare with the
575         // base directories of the projects in the reactor.
576 
577         if (aggregatedProject.getModules().isEmpty()) {
578             return Collections.singleton(aggregatedProject);
579         }
580 
581         List<Path> modulePaths = new LinkedList<Path>();
582         for (String module : aggregatedProject.getModules()) {
583             modulePaths.add(new File(aggregatedProject.getBasedir(), module).toPath());
584         }
585 
586         Set<MavenProject> aggregatedModules = new LinkedHashSet<>();
587 
588         for (Path modulePath : modulePaths) {
589             MavenProject module = reactorProjectsMap.remove(modulePath);
590             if (module != null) {
591                 aggregatedModules.addAll(modulesForAggregatedProject(module, reactorProjectsMap));
592             }
593         }
594 
595         return aggregatedModules;
596     }
597 }