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.checkstyle; 020 021import com.google.common.flogger.FluentLogger; 022import com.puppycrawl.tools.checkstyle.Checker; 023import com.puppycrawl.tools.checkstyle.ConfigurationLoader; 024import com.puppycrawl.tools.checkstyle.ConfigurationLoader.IgnoredModulesOptions; 025import com.puppycrawl.tools.checkstyle.PropertiesExpander; 026import com.puppycrawl.tools.checkstyle.api.AuditEvent; 027import com.puppycrawl.tools.checkstyle.api.AuditListener; 028import com.puppycrawl.tools.checkstyle.api.CheckstyleException; 029import com.puppycrawl.tools.checkstyle.api.SeverityLevel; 030import java.io.File; 031import java.nio.file.Files; 032import java.nio.file.Path; 033import java.util.Collection; 034import java.util.Collections; 035import java.util.List; 036import java.util.Properties; 037import java.util.function.Function; 038import org.jdrupes.builder.api.ConfigurationException; 039import org.jdrupes.builder.api.FileResource; 040import org.jdrupes.builder.api.FileTree; 041import org.jdrupes.builder.api.Generator; 042import org.jdrupes.builder.api.Project; 043import org.jdrupes.builder.api.Resource; 044import org.jdrupes.builder.api.ResourceRequest; 045import org.jdrupes.builder.api.ResourceType; 046import org.jdrupes.builder.api.Resources; 047import org.jdrupes.builder.core.AbstractGenerator; 048import static org.jdrupes.builder.ext.checkstyle.CheckstyleTypes.*; 049import org.jdrupes.builder.java.JavaSourceFile; 050 051/// A [Generator] that runs checkstyle on the project's Java sources. 052/// 053/// The checkstyle configuration is loaded from a file named 054/// `checkstyle.xml`. First, the project's directory is searched. If 055/// not found, the search continues in the parent project's directory 056/// and so on, up to the root project. The configuration path can also 057/// be set explicitly with [config]. 058/// 059/// Each style violation is printed to [context().error()]. The resulting 060/// [CheckstyleResult] contains summary counts. When errors are found, 061/// the result is flagged as faulty unless [ignoreFailed] was invoked. 062/// 063/// This provider is made available as an extension. 064/// [ 066/// ](https://codeberg.org/JDrupes/-/packages/maven/org.jdrupes:jdbld-ext-pmd/versions) 067/// 068public class CheckstyleChecker extends AbstractGenerator { 069 070 private static final FluentLogger logger 071 = FluentLogger.forEnclosingClass(); 072 073 private final Resources<FileTree<JavaSourceFile>> sources 074 = Resources.of(new ResourceType<>() {}); 075 private Path configPath; 076 private boolean ignoreFailed; 077 078 /// Initializes a new style checker. 079 /// 080 /// @param project the project 081 /// 082 public CheckstyleChecker(Project project) { 083 super(project); 084 } 085 086 /// Ignore errors. If invoked, the checker does not set the 087 /// faulty flag of the checkstyle result when errors have been found. 088 /// 089 /// @return the checkstyle checker 090 /// 091 public CheckstyleChecker ignoreFailed() { 092 this.ignoreFailed = true; 093 return this; 094 } 095 096 /// Sets the path to the checkstyle configuration file. The [Path] 097 /// is resolved against the project's directory when left relative. 098 /// 099 /// @param configPath the configuration file path 100 /// @return the style checker 101 /// 102 public CheckstyleChecker config(Path configPath) { 103 this.configPath = configPath; 104 return this; 105 } 106 107 /// Adds the source tree. 108 /// 109 /// @param sources the sources 110 /// @return the style checker 111 /// 112 public final CheckstyleChecker 113 addSources(FileTree<JavaSourceFile> sources) { 114 this.sources.add(sources); 115 return this; 116 } 117 118 /// Adds the files from the given directory matching the given pattern. 119 /// Short for 120 /// `addSources(FileTree.of(project(), directory, JavaSourceFile.class, pattern))`. 121 /// 122 /// @param directory the directory 123 /// @param pattern the pattern 124 /// @return the style checker 125 /// 126 public final CheckstyleChecker addSources(Path directory, String pattern) { 127 addSources(FileTree.of( 128 project(), directory, JavaSourceFile.class, pattern)); 129 return this; 130 } 131 132 /// Returns the source trees configured for the checker. 133 /// 134 /// @return the resources 135 /// 136 public Resources<FileTree<JavaSourceFile>> sources() { 137 return sources; 138 } 139 140 private Path findConfig() { 141 Project current = project(); 142 while (current != null) { 143 Path candidate = current.directory().resolve("checkstyle.xml"); 144 if (Files.exists(candidate)) { 145 return candidate; 146 } 147 if (current.equals(current.rootProject())) { 148 return null; 149 } 150 current = current.parentProject().orElse(null); 151 } 152 return null; 153 } 154 155 private List<File> sourceFiles() { 156 return sources.stream().map(Resources::stream) 157 .flatMap(Function.identity()).map(FileResource::path) 158 .map(Path::toFile).toList(); 159 } 160 161 @Override 162 protected <T extends Resource> Collection<T> doProvide( 163 ResourceRequest<T> requested) { 164 if (!requested.accepts(CheckstyleResultType)) { 165 return Collections.emptyList(); 166 } 167 if (!requested.isFor(CheckstyleResultType)) { 168 @SuppressWarnings("unchecked") 169 var result = (Collection<T>) resources(of(CheckstyleResultType)) 170 .toList(); 171 return result; 172 } 173 174 Path effectiveConfig = configPath; 175 if (effectiveConfig == null) { 176 effectiveConfig = findConfig(); 177 } 178 if (effectiveConfig == null) { 179 throw new ConfigurationException().from(this).message(""" 180 No checkstyle.xml found in this project, 181 its parent projects, or the root project. 182 Set config() explicitly."""); 183 } 184 185 logger.atInfo().log("Running checkstyle on %s with config %s", 186 project().name(), effectiveConfig); 187 188 var summary = new AuditSummary(); 189 List<File> files = sourceFiles(); 190 191 Checker checker = new Checker(); 192 try { 193 checker.setModuleClassLoader( 194 CheckstyleChecker.class.getClassLoader()); 195 var configuration = ConfigurationLoader.loadConfiguration( 196 effectiveConfig.toString(), 197 new PropertiesExpander(new Properties()), 198 IgnoredModulesOptions.EXECUTE); 199 checker.configure(configuration); 200 checker.addListener(summary); 201 202 int errors = checker.process(files); 203 checker.destroy(); 204 long checked = summary.checkedCount(); 205 long warnings = summary.warningsCount(); 206 207 var result = CheckstyleResult.of(project(), this, checked, 208 errors, warnings); 209 if (errors > 0 && !ignoreFailed) { 210 result.setFaulty(); 211 } 212 @SuppressWarnings("unchecked") 213 var asList = List.of((T) result); 214 return asList; 215 } catch (CheckstyleException e) { 216 throw new ConfigurationException().from(this).cause(e) 217 .message("CheckstyleChecker failed: %s", e.getMessage()); 218 } finally { 219 checker.destroy(); 220 } 221 } 222 223 /// Counts checked files and delegates violation output to context. 224 /// 225 private final class AuditSummary implements AuditListener { 226 227 private int checkedCount; 228 private long warningsCount; 229 230 /// Return the number of files checked. 231 /// 232 /// @return the int 233 /// 234 /* default */ int checkedCount() { 235 return checkedCount; 236 } 237 238 /// Return the number of warnings. 239 /// 240 /// @return the long 241 /// 242 /* default */ long warningsCount() { 243 return warningsCount; 244 } 245 246 @Override 247 public void auditStarted(AuditEvent event) { 248 // Not tracked 249 } 250 251 @Override 252 public void auditFinished(AuditEvent event) { 253 // Not tracked 254 } 255 256 @Override 257 public void fileStarted(AuditEvent event) { 258 checkedCount++; 259 } 260 261 @Override 262 public void fileFinished(AuditEvent event) { 263 // Not tracked 264 } 265 266 @Override 267 public void addError(AuditEvent event) { 268 if (event.getSeverityLevel() == SeverityLevel.WARNING) { 269 warningsCount++; 270 } 271 context().error().format("[%s] %s:%d:%d: %s%n", 272 project(), 273 project().directory().relativize(Path.of(event.getFileName())), 274 event.getLine(), event.getColumn(), event.getMessage()); 275 } 276 277 @Override 278 public void addException(AuditEvent event, Throwable throwable) { 279 logger.atWarning().withCause(throwable) 280 .log("CheckstyleChecker exception in %s", event.getFileName()); 281 } 282 } 283}