View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.pmd;
6   
7   import com.jcabi.log.Logger;
8   import com.qulice.spi.Environment;
9   import com.qulice.spi.Relative;
10  import com.qulice.spi.ResourceValidator;
11  import com.qulice.spi.Violation;
12  import java.io.File;
13  import java.util.Collection;
14  import java.util.LinkedList;
15  
16  /**
17   * Validates source code with PMD.
18   * @since 0.3
19   */
20  public final class PmdValidator implements ResourceValidator {
21  
22      /**
23       * Environment to use.
24       */
25      private final transient Environment env;
26  
27      /**
28       * Constructor.
29       * @param env Environment to use
30       */
31      public PmdValidator(final Environment env) {
32          this.env = env;
33      }
34  
35      @Override
36      public Collection<Violation> validate(final Collection<File> files) {
37          final Collection<File> sources = this.getNonExcludedFiles(files);
38          final Collection<Violation> violations = new LinkedList<>();
39          if (sources.isEmpty()) {
40              Logger.debug(
41                  this,
42                  "No files to check with PMD, all %d are excluded",
43                  files.size()
44              );
45          } else {
46              final SourceValidator validator = new SourceValidator(this.env.encoding());
47              final Collection<PmdError> errors = validator.validate(
48                  sources, this.env.basedir().getPath()
49              );
50              for (final PmdError error : errors) {
51                  violations.add(
52                      new Violation.Default(
53                          this.name(),
54                          error.name(),
55                          error.fileName(),
56                          error.lines(),
57                          error.description()
58                      )
59                  );
60              }
61          }
62          return violations;
63      }
64  
65      @Override
66      public String name() {
67          return "PMD";
68      }
69  
70      /**
71       * Filters out excluded files from further validation.
72       * @param files Files to validate
73       * @return Relevant source files
74       */
75      public Collection<File> getNonExcludedFiles(final Collection<File> files) {
76          final Collection<File> sources = new LinkedList<>();
77          for (final File file : files) {
78              final String name = new Relative(this.env.basedir(), file).path();
79              if (this.env.exclude("pmd", name)) {
80                  continue;
81              }
82              if (!name.matches("^.*\\.java$")) {
83                  continue;
84              }
85              sources.add(file);
86          }
87          return sources;
88      }
89  }