001/* 002 * JDrupes Builder 003 * Copyright (C) 2026 Michael N. Lipp 004 * 005 * This program is free software: you can redistribute it and/or modify 006 * it under the terms of the GNU Affero General Public License as 007 * published by the Free Software Foundation, either version 3 of the 008 * License, or (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU Affero General Public License for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License 016 * along with this program. If not, see <https://www.gnu.org/licenses/>. 017 */ 018 019package org.jdrupes.builder.ext.pmd; 020 021import com.google.common.flogger.FluentLogger; 022import java.nio.file.Files; 023import java.nio.file.Path; 024import java.util.Collection; 025import java.util.Collections; 026import java.util.List; 027import java.util.function.Function; 028import net.sourceforge.pmd.PMDConfiguration; 029import net.sourceforge.pmd.PmdAnalysis; 030import net.sourceforge.pmd.lang.rule.RuleSetLoadException; 031import net.sourceforge.pmd.reporting.Report; 032import net.sourceforge.pmd.reporting.Report.ProcessingError; 033import net.sourceforge.pmd.reporting.RuleViolation; 034import org.jdrupes.builder.api.ConfigurationException; 035import org.jdrupes.builder.api.FileResource; 036import org.jdrupes.builder.api.FileTree; 037import org.jdrupes.builder.api.Generator; 038import org.jdrupes.builder.api.Project; 039import org.jdrupes.builder.api.Resource; 040import org.jdrupes.builder.api.ResourceRequest; 041import org.jdrupes.builder.api.ResourceType; 042import org.jdrupes.builder.api.Resources; 043import org.jdrupes.builder.core.AbstractGenerator; 044import static org.jdrupes.builder.ext.pmd.PmdTypes.*; 045import org.jdrupes.builder.java.JavaSourceFile; 046 047/// A [Generator] that runs PMD on the project's Java sources. 048/// 049/// The PMD ruleset configuration is loaded from a file named 050/// `pmd.xml`. First, the project's directory is searched. If not 051/// found, the search continues in the parent project's directory and 052/// so on, up to the root project. The configuration path can also be 053/// set explicitly with [config]. 054/// 055/// Each rule violation is printed to [context().error()]. The 056/// resulting [PmdResult] contains summary counts and is never flagged 057/// as faulty. 058/// 059/// This provider is made available as an extension. 060/// [ 062/// ](https://codeberg.org/JDrupes/-/packages/maven/org.jdrupes:jdbld-ext-checkstyle/versions) 063/// 064public class PmdChecker extends AbstractGenerator { 065 066 private static final FluentLogger logger 067 = FluentLogger.forEnclosingClass(); 068 069 private final Resources<FileTree<JavaSourceFile>> sources 070 = Resources.of(new ResourceType<>() {}); 071 private Path configPath; 072 073 /// Initializes a new PMD checker. 074 /// 075 /// @param project the project 076 /// 077 public PmdChecker(Project project) { 078 super(project); 079 } 080 081 /// Sets the path to the PMD ruleset configuration file. The [Path] 082 /// is resolved against the project's directory when left relative. 083 /// 084 /// @param configPath the configuration file path 085 /// @return the PMD checker 086 /// 087 public PmdChecker config(Path configPath) { 088 this.configPath = configPath; 089 return this; 090 } 091 092 /// Adds the source tree. 093 /// 094 /// @param sources the sources 095 /// @return the PMD checker 096 /// 097 public final PmdChecker addSources(FileTree<JavaSourceFile> sources) { 098 this.sources.add(sources); 099 return this; 100 } 101 102 /// Adds the files from the given directory matching the given pattern. 103 /// Short for 104 /// `addSources(FileTree.of(project(), directory, JavaSourceFile.class, pattern))`. 105 /// 106 /// @param directory the directory 107 /// @param pattern the pattern 108 /// @return the PMD checker 109 /// 110 public final PmdChecker addSources(Path directory, String pattern) { 111 addSources(FileTree.of( 112 project(), directory, JavaSourceFile.class, pattern)); 113 return this; 114 } 115 116 /// Returns the source trees configured for the checker. 117 /// 118 /// @return the resources 119 /// 120 public Resources<FileTree<JavaSourceFile>> sources() { 121 return sources; 122 } 123 124 @Override 125 protected <T extends Resource> Collection<T> doProvide( 126 ResourceRequest<T> requested) { 127 if (!requested.accepts(PmdResultType)) { 128 return Collections.emptyList(); 129 } 130 if (!requested.isFor(PmdResultType)) { 131 @SuppressWarnings("unchecked") 132 var result = (Collection<T>) resources(of(PmdResultType)) 133 .toList(); 134 return result; 135 } 136 137 Path effectiveConfig = configPath; 138 if (effectiveConfig == null) { 139 effectiveConfig = findConfig(); 140 } 141 if (effectiveConfig == null) { 142 throw new ConfigurationException().from(this).message(""" 143 No configuration file found."""); 144 } 145 146 logger.atInfo().log("Running PMD on %s with ruleset %s", 147 project().name(), effectiveConfig); 148 149 List<Path> files = sourceFiles(); 150 int checkedCount = 0; 151 152 PMDConfiguration config = new PMDConfiguration(); 153 config.setIgnoreIncrementalAnalysis(true); 154 config.addRelativizeRoot(project().directory()); 155 156 try (PmdAnalysis analysis = PmdAnalysis.create(config)) { 157 try { 158 analysis.addRuleSet( 159 analysis.newRuleSetLoader() 160 .loadFromResource(effectiveConfig.toString())); 161 } catch (RuleSetLoadException e) { 162 throw new ConfigurationException() 163 .from(this).cause(e).message(""" 164 Could not load PMD ruleset from %s.""", 165 effectiveConfig); 166 } 167 168 for (Path file : files) { 169 analysis.files().addFile(file); 170 checkedCount++; 171 } 172 173 Report report = analysis.performAnalysisAndCollectReport(); 174 175 for (ProcessingError error : report.getProcessingErrors()) { 176 logger.atFiner().withCause(error.getError()) 177 .log("[%s] %s: %s%n", project(), error.getFileId(), 178 error.getMsg()); 179 } 180 for (RuleViolation violation : report.getViolations()) { 181 context().error().format("[%s] %s:%d:%d: %s [%s]%n", 182 project(), project().directory().relativize( 183 Path.of(violation.getFileId().getAbsolutePath())), 184 violation.getBeginLine(), 185 violation.getBeginColumn(), 186 violation.getDescription(), 187 violation.getRule().getName()); 188 } 189 190 var result = PmdResult.of(project(), this, checkedCount, 191 (long) report.getViolations().size()); 192 @SuppressWarnings("unchecked") 193 var asList = List.of((T) result); 194 return asList; 195 } 196 } 197 198 private Path findConfig() { 199 Project current = project(); 200 while (current != null) { 201 Path candidate = current.directory().resolve("pmd.xml"); 202 if (Files.exists(candidate)) { 203 return candidate; 204 } 205 if (current.equals(current.rootProject())) { 206 return null; 207 } 208 current = current.parentProject().orElse(null); 209 } 210 return null; 211 } 212 213 private List<Path> sourceFiles() { 214 return sources.stream().map(Resources::stream) 215 .flatMap(Function.identity()).map(FileResource::path) 216 .toList(); 217 } 218}