diff --git a/gradle/pinned-libs.versions.toml b/gradle/pinned-libs.versions.toml index 9f645d1161..3c8e83eea6 100644 --- a/gradle/pinned-libs.versions.toml +++ b/gradle/pinned-libs.versions.toml @@ -15,3 +15,9 @@ google-java-format = "com.google.googlejavaformat:google-java-format:1.28.0" diktat-rules = "org.cqfn.diktat:diktat-rules:1.2.5" aether-api = "org.eclipse.aether:aether-api:1.1.0" plexus-build-api = "org.sonatype.plexus:plexus-build-api:0.0.7" +# API floor for the spotless:report goal. maven-site-plugin supplies its own copy at runtime, and the report +# only calls methods that Doxia 1 (maven-site-plugin 3.12.x) has too, so don't raise these casually. +maven-reporting-api = "org.apache.maven.reporting:maven-reporting-api:4.0.0" +doxia-sink-api = "org.apache.maven.doxia:doxia-sink-api:2.0.0" +# Xpp3Dom, which Maven 3 supplies at runtime; plexus-utils 4 moved it out into plexus-xml. +plexus-xml = "org.codehaus.plexus:plexus-xml:3.0.1" diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index 4081c6671e..d609360ba8 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -3,6 +3,9 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `1.27.0`). ## [Unreleased] +### Added +- Add a `spotless:report` goal that puts a Spotless page in the Maven site. ([#3175](https://github.com/diffplug/spotless/pull/3175)) + List `spotless-maven-plugin` under `` and run `mvn site`: the page shows which files need formatting, with a colored diff for each, and their lint problems. It works with `maven-site-plugin` 3.12.1 and 3.20.0 or later. ### Fixed - GrEclipse no longer leaves a `file%3A...` directory in the working directory. ([#2019](https://github.com/diffplug/spotless/issues/2019)) diff --git a/plugin-maven/README.md b/plugin-maven/README.md index 3fae9b808d..0065c0cfe6 100644 --- a/plugin-maven/README.md +++ b/plugin-maven/README.md @@ -72,6 +72,7 @@ user@machine repo % mvn spotless:check - [Line endings and encodings (invisible stuff)](#line-endings-and-encodings-invisible-stuff) - [Disabling warnings and error messages](#disabling-warnings-and-error-messages) - [How do I preview what `mvn spotless:apply` will do?](#how-do-i-preview-what-mvn-spotlessapply-will-do) + - [Maven site report](#maven-site-report) - [Can I apply Spotless to specific files?](#can-i-apply-spotless-to-specific-files) - [How to centralize Spotless configuration](#central-configuration) - [Example configurations (from real-world projects)](#example-configurations-from-real-world-projects) @@ -2173,15 +2174,17 @@ By default, `spotless:check` is bound to the `verify` phase. You might want to d | Property | Scope | Effect | | --- | --- | --- | -| `spotless.skip` | `spotless:check` and `spotless:apply` | Skips both formatting goals | +| `spotless.skip` | `spotless:check`, `spotless:apply` and `spotless:report` | Skips all three goals | | `spotless.check.skip` | `spotless:check` only | Skips only the check goal | | `spotless.apply.skip` | `spotless:apply` only | Skips only the apply goal | +| `spotless.report.skip` | `spotless:report` only | Skips only the [site report](#maven-site-report) | You can set them at the command line or in the `` section of the `pom.xml`: -- `-Dspotless.skip=true` / `true` — skip both `spotless:check` and `spotless:apply` +- `-Dspotless.skip=true` / `true` — skip `spotless:check`, `spotless:apply` and `spotless:report` - `-Dspotless.check.skip=true` / `true` — skip only `spotless:check` (including when it is bound to `verify`) - `-Dspotless.apply.skip=true` / `true` — skip only `spotless:apply` +- `-Dspotless.report.skip=true` / `true` — skip only `spotless:report` `spotless.check.skip` does **not** skip `spotless:apply`, and `spotless.apply.skip` does **not** skip `spotless:check`. Use `spotless.skip` when you want both. These properties do **not** affect `spotless:install-git-pre-push-hook`. @@ -2253,6 +2256,36 @@ Spotless is primarily a formatter, _not_ a linter. In our opinion, a linter is j - If you don't like what spotless did, `git reset --hard` - If you'd like to remove the "checkpoint" commit, `git reset --soft head~1` will make the checkpoint commit "disappear" from history, but keeps the changes in your working directory. +You can also look at the changes without applying them, in the [site report](#maven-site-report). + +## Maven site report + +`spotless:report` adds a **Spotless** page to the site that `mvn site` builds. List the plugin in the `` section of your `pom.xml`: + +```xml + + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless.version} + + + +``` + +You don't need to repeat your Spotless configuration: the report uses the plugin-level `` of the Spotless plugin in your `` section, except for anything you set in `` itself. Configuration inside an `` is not used. + +`mvn site` then lists Spotless under *Project Reports*. The page shows, for each format, how many files are clean, need formatting or have lint problems. Each file with a problem gets its own page, with a colored diff of the changes `mvn spotless:apply` would make and a table of its lint problems. + +The report checks the same files as `spotless:check`, so `ratchetFrom`, `spotlessFiles` and `` apply to it. It never changes your files, never fails the build because of violations, and ignores the [up-to-date index](#incremental-up-to-date-checking-and-formatting), so every file is checked. + +- `mvn spotless:report` writes the report to `target/site/spotless.html` without building the whole site. Run this way, it reads only the configuration in ``, because Maven never applies `` to goals you run directly. If you use both, put report options such as `` in ``. +- `` (default `1000`, `0` for no limit) limits how many lines of diff each file's page shows. `-Dspotless.report.maxDiffLines` sets it from the command line. +- `-Dspotless.report.skip=true` skips the report, and so does `-Dspotless.skip=true`. + +The report works with `maven-site-plugin` 3.12.1, which Maven 3.9 uses by default, and with 3.20.0 or later. + ## Can I apply Spotless to specific files? You can target specific files by setting the `spotlessFiles` project property to a comma-separated list of file patterns: diff --git a/plugin-maven/build.gradle.kts b/plugin-maven/build.gradle.kts index 62511b936d..ee77a8c1e9 100644 --- a/plugin-maven/build.gradle.kts +++ b/plugin-maven/build.gradle.kts @@ -40,6 +40,7 @@ dependencies { compileOnly(pinnedLibs.maven.plugin.annotations) compileOnly(pinnedLibs.maven.core) compileOnly(pinnedLibs.aether.api) + compileOnly(pinnedLibs.plexus.xml) compileOnly(libs.jakarta.annotation.api) compileOnly(libs.javax.inject) @@ -51,6 +52,9 @@ dependencies { implementation(libs.plexus.utils) implementation(libs.jgit) implementation(pinnedLibs.plexus.build.api) + // spotless:report; only these two small API jars, no Doxia renderer + implementation(pinnedLibs.maven.reporting.api) + implementation(pinnedLibs.doxia.sink.api) testImplementation(projects.testlib) testImplementation(libs.junit.jupiter) diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java index 58c876300d..e7401be073 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java @@ -102,6 +102,7 @@ public abstract class AbstractSpotlessMojo extends AbstractMojo { static final String GOAL_CHECK = "check"; static final String GOAL_APPLY = "apply"; static final String GOAL_PRE_PUSH_HOOK = "install-git-pre-push-hook"; + static final String GOAL_REPORT = "report"; @Inject private RepositorySystem repositorySystem; @@ -290,9 +291,26 @@ public final void execute() throws MojoExecutionException { } catch (PluginException e) { throw e.asMojoExecutionException(); } + afterProcessing(); } - private boolean shouldSkip() { + /** + * Called once after every format has been processed and the formatters have been closed. + * Goals that collect results in {@link #process}, such as {@code spotless:report}, act on them here. + */ + protected void afterProcessing() throws MojoExecutionException {} + + /** + * Whether this goal uses the up-to-date index, which skips files that were clean the last time + * {@code spotless:check} or {@code spotless:apply} ran. Goals that must look at every file without + * touching that index, such as {@code spotless:report}, return {@code false}. + */ + protected boolean usesUpToDateIndex() { + return true; + } + + /** Returns {@code true} if this goal should do nothing, because of {@code spotless.skip}, a goal-specific skip flag, or an m2e incremental build. */ + protected final boolean shouldSkip() { if (skip) { return true; } @@ -463,6 +481,9 @@ private List getFormatterStepFactories() { } private UpToDateChecker createUpToDateChecker(Iterable formatters) { + if (!usesUpToDateIndex()) { + return UpToDateChecker.ignoringIndex(); + } Path indexFile = upToDateChecking == null ? null : upToDateChecking.getIndexFile(); if (indexFile == null) { Path targetDir = project.getBasedir().toPath().resolve(project.getBuild().getDirectory()); diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessReportMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessReportMojo.java new file mode 100644 index 0000000000..8fc7dc64ca --- /dev/null +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessReportMojo.java @@ -0,0 +1,296 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.maven; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Named; + +import org.apache.maven.doxia.sink.Sink; +import org.apache.maven.doxia.sink.SinkFactory; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.model.Plugin; +import org.apache.maven.model.ReportPlugin; +import org.apache.maven.model.ReportSet; +import org.apache.maven.model.Reporting; +import org.apache.maven.plugin.MojoExecution; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.PluginParameterExpressionEvaluator; +import org.apache.maven.plugin.descriptor.PluginDescriptor; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; +import org.apache.maven.reporting.MavenMultiPageReport; +import org.apache.maven.reporting.MavenReport; +import org.apache.maven.reporting.MavenReportException; +import org.codehaus.plexus.component.configurator.ComponentConfigurationException; +import org.codehaus.plexus.component.configurator.ComponentConfigurator; +import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; +import org.codehaus.plexus.util.xml.Xpp3Dom; + +import com.diffplug.spotless.Formatter; +import com.diffplug.spotless.LintState; +import com.diffplug.spotless.maven.incremental.UpToDateChecker; +import com.diffplug.spotless.maven.report.SpotlessReport; + +/** + * Adds a Spotless page to the Maven site: list the plugin under {@code } and run {@code mvn site}. + * Running {@code mvn spotless:report} writes the same pages without building the whole site. + *

+ * The report covers the same files as {@code spotless:check} and shows the changes {@code spotless:apply} would + * make, but it never changes a file, never fails the build because of violations, and ignores the up-to-date index. + *

+ * {@code mvn site} configures report goals only from {@code } and {@code }, not + * from {@code }, where most projects configure Spotless. So the report copies the plugin-level + * configuration from there, except for parameters that {@code } sets itself. When you run + * {@code mvn spotless:report} directly, Maven configures it from {@code } only, never from + * {@code }. + *

+ * The report is a {@link MavenMultiPageReport} built against the Doxia 2 API, using only calls that Doxia 1 has + * too, so it works with {@code maven-site-plugin} 3.12.x (Maven 3.9's default) and 3.20 or later: both call + * {@link #generate(Sink, SinkFactory, Locale)}, whose signature did not change between the two. + */ +@Mojo(name = AbstractSpotlessMojo.GOAL_REPORT, threadSafe = true) +public class SpotlessReportMojo extends AbstractSpotlessMojo implements MavenMultiPageReport { + private static final String OUTPUT_NAME = "spotless"; + + /** Skips the report. {@code spotless.skip} skips it too. */ + @Parameter(property = "spotless.report.skip", defaultValue = "false") + private boolean reportSkip; + + /** + * Where {@code mvn spotless:report} writes the report. {@code mvn site} always writes it to the site's output + * directory instead. + */ + @Parameter(defaultValue = "${project.reporting.outputDirectory}", required = true) + private File outputDirectory; + + /** + * The most lines of diff shown for one file. Longer diffs are cut off, with a note saying how many lines are + * hidden. {@code 0} or less shows whole diffs. + */ + @Parameter(property = "spotless.report.maxDiffLines", defaultValue = "1000") + private int maxDiffLines; + + @Parameter(defaultValue = "${session}", readonly = true, required = true) + private MavenSession session; + + @Parameter(defaultValue = "${mojoExecution}", readonly = true, required = true) + private MojoExecution mojoExecution; + + @Inject + @Named("basic") + private ComponentConfigurator configurator; + + /** Filled by {@link #process}; {@code null} until the first format is processed. */ + private SpotlessReport report; + /** Set by {@code mvn site}, which renders the pages itself, through {@link #generate}. */ + private boolean renderingForSite; + private boolean usedBuildConfiguration; + private MavenReportException buildConfigurationError; + + @Override + protected boolean isGoalSpecificSkip() { + return reportSkip; + } + + @Override + protected boolean usesUpToDateIndex() { + return false; + } + + @Override + protected void process(String name, Iterable files, Formatter formatter, UpToDateChecker upToDateChecker) { + if (report == null) { + report = new SpotlessReport(maxDiffLines); + } + SpotlessReport.Format format = report.addFormat(name, formatter); + for (File file : files) { + String path = relativePath(file); + try { + LintState lintState = calculateLintState(formatter, file); + byte[] rawBytes = Files.readAllBytes(file.toPath()); + format.addFile(path, lintState, rawBytes, formatter); + } catch (IOException | RuntimeException e) { + getLog().warn("Spotless could not check " + path + ": " + e.getMessage()); + getLog().debug(e); + format.addError(path, e); + } + } + } + + private String relativePath(File file) { + try { + return baseDir.toPath().toAbsolutePath().relativize(file.toPath().toAbsolutePath()).toString().replace(File.separatorChar, '/'); + } catch (IllegalArgumentException e) { + // on Windows, a file on another drive has no relative path + return file.getAbsolutePath().replace(File.separatorChar, '/'); + } + } + + @Override + protected void afterProcessing() throws MojoExecutionException { + if (report == null) { + // no formats are configured + report = new SpotlessReport(maxDiffLines); + } + getLog().info(report.summary()); + if (renderingForSite) { + return; + } + try { + File page = report.writeStandalone(outputDirectory, OUTPUT_NAME); + getLog().info("Spotless report written to " + page); + } catch (IOException e) { + throw new MojoExecutionException("Unable to write the Spotless report to " + outputDirectory, e); + } + } + + @Override + public void generate(Sink sink, Locale locale) throws MavenReportException { + generate(sink, null, locale); + } + + @Override + public void generate(Sink sink, SinkFactory sinkFactory, Locale locale) throws MavenReportException { + renderingForSite = true; + useBuildConfiguration(); + if (buildConfigurationError != null) { + throw buildConfigurationError; + } + // analyze on every call, because mvn site:run renders the same report instance again for each request + report = null; + try { + execute(); + } catch (MojoExecutionException e) { + throw new MavenReportException(e.getMessage(), e); + } + if (report == null) { + report = new SpotlessReport(maxDiffLines); + } + try { + report.render(sink, sinkFactory, getReportOutputDirectory(), OUTPUT_NAME); + } catch (IOException e) { + throw new MavenReportException("Unable to render the Spotless report", e); + } + } + + @Override + public boolean canGenerateReport() { + // before deciding, so that a in the configuration counts too + useBuildConfiguration(); + return buildConfigurationError != null || !shouldSkip(); + } + + /** + * Copies the plugin-level configuration of this plugin in {@code } onto this goal, except for + * parameters that {@code } sets itself. {@code mvn site} only applies the configuration from + * {@code } and {@code }. Runs once; a failure is kept for {@link #generate}. + */ + private void useBuildConfiguration() { + if (usedBuildConfiguration) { + return; + } + usedBuildConfiguration = true; + PluginDescriptor plugin = mojoExecution.getMojoDescriptor().getPluginDescriptor(); + String key = plugin.getGroupId() + ":" + plugin.getArtifactId(); + MavenProject project = session.getCurrentProject(); + Plugin buildPlugin = project.getPlugin(key); + if (buildPlugin == null || !(buildPlugin.getConfiguration() instanceof Xpp3Dom buildConfiguration)) { + return; + } + Set setInReporting = new HashSet<>(); + // maven-site-plugin sets the output directory to the site directory just before canGenerateReport(), keep that + setInReporting.add("outputDirectory"); + Reporting reporting = project.getModel().getReporting(); + if (reporting != null) { + for (ReportPlugin reportPlugin : reporting.getPlugins()) { + if (key.equals(reportPlugin.getGroupId() + ":" + reportPlugin.getArtifactId())) { + addChildNames(reportPlugin.getConfiguration(), setInReporting); + for (ReportSet reportSet : reportPlugin.getReportSets()) { + addChildNames(reportSet.getConfiguration(), setInReporting); + } + } + } + } + Set parameters = mojoExecution.getMojoDescriptor().getParameterMap().keySet(); + Xpp3Dom inherited = new Xpp3Dom("configuration"); + for (Xpp3Dom child : buildConfiguration.getChildren()) { + if (parameters.contains(child.getName()) && !setInReporting.contains(child.getName())) { + inherited.addChild(new Xpp3Dom(child)); + } + } + if (inherited.getChildCount() == 0) { + return; + } + try { + configurator.configureComponent(this, new XmlPlexusConfiguration(inherited), new PluginParameterExpressionEvaluator(session, mojoExecution), plugin.getClassRealm()); + } catch (ComponentConfigurationException e) { + buildConfigurationError = new MavenReportException("Unable to use the Spotless configuration from for the report: " + e.getMessage(), e); + } + } + + private static void addChildNames(Object configuration, Set names) { + if (configuration instanceof Xpp3Dom dom) { + for (Xpp3Dom child : dom.getChildren()) { + names.add(child.getName()); + } + } + } + + /** Deprecated in maven-reporting-api 4 in favor of {@code getOutputPath()}, but it's the only one maven-site-plugin 3.12.x calls. */ + @Override + @SuppressWarnings("deprecation") + public String getOutputName() { + return OUTPUT_NAME; + } + + @Override + public String getCategoryName() { + return MavenReport.CATEGORY_PROJECT_REPORTS; + } + + @Override + public String getName(Locale locale) { + return "Spotless"; + } + + @Override + public String getDescription(Locale locale) { + return "Files that do not match the Spotless formatting rules, the changes spotless:apply would make to them, and lint problems."; + } + + @Override + public void setReportOutputDirectory(File outputDirectory) { + this.outputDirectory = outputDirectory; + } + + @Override + public File getReportOutputDirectory() { + return outputDirectory; + } + + @Override + public boolean isExternalReport() { + return false; + } +} diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecker.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecker.java index c5c734a4d7..2e8f1d386f 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecker.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2025 DiffPlug + * Copyright 2021-2026 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,6 +36,25 @@ static UpToDateChecker noop(MavenProject project, Path indexFile, Log log) { return NoopChecker.create(project, indexFile, log); } + /** + * A checker that never reads, writes or deletes the up-to-date index, so every file is processed. + * Unlike {@link #noop}, it leaves the index used by {@code spotless:check} and {@code spotless:apply} alone. + */ + static UpToDateChecker ignoringIndex() { + return new UpToDateChecker() { + @Override + public boolean isUpToDate(Path file) { + return false; + } + + @Override + public void setUpToDate(Path file) {} + + @Override + public void close() {} + }; + } + static UpToDateChecker forProject(MavenProject project, Path indexFile, Iterable formatters, Log log) { return IndexBasedChecker.create(project, indexFile, formatters, log); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/Html.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/Html.java new file mode 100644 index 0000000000..a377541a5e --- /dev/null +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/Html.java @@ -0,0 +1,62 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.maven.report; + +final class Html { + private Html() {} + + /** + * Escapes text for HTML element content and quoted attribute values. The result is pure ASCII: {@code $} and + * every non-ASCII character become numeric references. That's because the site renderer replaces + * {@code $relativePath} in everything it writes, and writes raw HTML in the site's output encoding, which may not + * be able to represent every character. + */ + static String escape(String text) { + StringBuilder escaped = new StringBuilder(text.length() + 16); + for (int i = 0; i < text.length();) { + int codePoint = text.codePointAt(i); + i += Character.charCount(codePoint); + switch (codePoint) { + case '&': + escaped.append("&"); + break; + case '<': + escaped.append("<"); + break; + case '>': + escaped.append(">"); + break; + case '"': + escaped.append("""); + break; + case '\'': + escaped.append("'"); + break; + case '$': + escaped.append("$"); + break; + default: + if (codePoint > 0x7E) { + escaped.append("&#x").append(Integer.toHexString(codePoint)).append(';'); + } else { + escaped.append((char) codePoint); + } + break; + } + } + return escaped.toString(); + } +} diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/HtmlSink.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/HtmlSink.java new file mode 100644 index 0000000000..50439a1e1f --- /dev/null +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/HtmlSink.java @@ -0,0 +1,148 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.maven.report; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.io.Writer; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Map; + +import org.apache.maven.doxia.sink.Sink; + +/** + * A minimal {@link Sink} that writes a self-contained HTML page, for {@code mvn spotless:report} outside of + * {@code mvn site}. It handles the events {@link ReportRenderer} emits and ignores the rest, so the plugin + * does not need Doxia's renderers. + */ +final class HtmlSink implements InvocationHandler { + private static final String STYLE = "body{font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Helvetica,Arial,sans-serif;" + + "max-width:1100px;margin:2em auto;padding:0 1em;color:#1f2328;line-height:1.5}" + + "h1{font-size:1.8em;border-bottom:1px solid #d0d7de;padding-bottom:.3em}h2{font-size:1.4em;margin-top:1.5em}" + + "table{border-collapse:collapse;margin:.5em 0 1em}" + + "th,td{border:1px solid #d0d7de;padding:4px 10px;text-align:left;vertical-align:top}th{background:#f6f8fa}" + + "code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:90%}" + + "a{color:#0969da;text-decoration:none}a:hover{text-decoration:underline}"; + + private static final Map TAGS = Map.ofEntries( + Map.entry("head_", "\n"), + Map.entry("title", ""), + Map.entry("title_", "\n"), + Map.entry("body", "\n"), + Map.entry("body_", "\n\n"), + Map.entry("section1", "

\n"), + Map.entry("section1_", "
\n"), + Map.entry("section2", "
\n"), + Map.entry("section2_", "
\n"), + Map.entry("section3", "
\n"), + Map.entry("section3_", "
\n"), + Map.entry("section4", "
\n"), + Map.entry("section4_", "
\n"), + Map.entry("sectionTitle1", "

"), + Map.entry("sectionTitle1_", "

\n"), + Map.entry("sectionTitle2", "

"), + Map.entry("sectionTitle2_", "

\n"), + Map.entry("sectionTitle3", "

"), + Map.entry("sectionTitle3_", "

\n"), + Map.entry("sectionTitle4", "

"), + Map.entry("sectionTitle4_", "

\n"), + Map.entry("paragraph", "

"), + Map.entry("paragraph_", "

\n"), + Map.entry("table", "\n"), + Map.entry("table_", "
\n"), + Map.entry("tableRows", ""), + Map.entry("tableRows_", ""), + Map.entry("tableRow", ""), + Map.entry("tableRow_", "\n"), + Map.entry("tableHeaderCell", ""), + Map.entry("tableHeaderCell_", ""), + Map.entry("tableCell", ""), + Map.entry("tableCell_", ""), + Map.entry("list", "
    \n"), + Map.entry("list_", "
\n"), + Map.entry("listItem", "
  • "), + Map.entry("listItem_", "
  • \n"), + Map.entry("link_", ""), + Map.entry("anchor_", ""), + Map.entry("bold", ""), + Map.entry("bold_", ""), + Map.entry("italic", ""), + Map.entry("italic_", ""), + Map.entry("monospaced", ""), + Map.entry("monospaced_", ""), + Map.entry("lineBreak", "
    \n"), + Map.entry("horizontalRule", "
    \n")); + + private final Writer out; + + private HtmlSink(Writer out) { + this.out = out; + } + + /** Returns a sink that writes HTML to {@code out}, and closes it when the sink is closed. */ + static Sink create(Writer out) { + return (Sink) Proxy.newProxyInstance(Sink.class.getClassLoader(), new Class[]{Sink.class}, new HtmlSink(out)); + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) { + String name = method.getName(); + try { + String tag = TAGS.get(name); + if (tag != null) { + out.write(tag); + return null; + } + switch (name) { + case "head": + out.write("\n\n\n\n" + + "\n\n"); + return null; + case "text": + out.write(Html.escape(String.valueOf(args[0]))); + return null; + case "rawText": + out.write(String.valueOf(args[0])); + return null; + case "link": + out.write(""); + return null; + case "anchor": + out.write(""); + return null; + case "flush": + out.flush(); + return null; + case "close": + out.close(); + return null; + case "hashCode": + return System.identityHashCode(proxy); + case "equals": + return proxy == args[0]; + case "toString": + return "HtmlSink"; + default: + // an event the report never emits, such as comment() + return null; + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/ReportRenderer.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/ReportRenderer.java new file mode 100644 index 0000000000..052d12625a --- /dev/null +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/ReportRenderer.java @@ -0,0 +1,667 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.maven.report; + +import static com.diffplug.spotless.maven.report.SpotlessReport.count; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import org.apache.maven.doxia.sink.Sink; + +import com.diffplug.spotless.maven.report.SpotlessReport.Changes; +import com.diffplug.spotless.maven.report.SpotlessReport.FileResult; +import com.diffplug.spotless.maven.report.SpotlessReport.Format; +import com.diffplug.spotless.maven.report.SpotlessReport.LintRow; + +/** + * Renders a {@link SpotlessReport} through the Doxia {@link Sink} API. + *

    + * It only calls {@code Sink} methods that exist with the same signature in Doxia 1.11 and Doxia 2.0, so the same + * plugin works with {@code maven-site-plugin} 3.12.x (Doxia 1, Maven 3.9's default) and 3.20 or later (Doxia 2). + * In particular it avoids {@code verbatim()}, {@code verbatim(boolean)}, {@code tableRows()}, + * {@code tableCell(String)} and {@code tableHeaderCell(String)}, and it closes sinks explicitly instead of with + * try-with-resources, because the Doxia 1 {@code Sink} is not {@link AutoCloseable}. + */ +final class ReportRenderer { + /** Opens the sink for another page, given its file name next to the summary page. */ + @FunctionalInterface + interface PageSinks { + Sink open(String fileName) throws IOException; + } + + private static final String PADDED_CELL_URL = "https://github.com/diffplug/spotless/blob/main/PADDEDCELL.md"; + + private static final String CLEAN_COLOR = "#2da44e"; + private static final String FORMATTING_COLOR = "#cf222e"; + private static final String LINT_COLOR = "#bf8700"; + private static final String NOT_CONVERGING_COLOR = "#8250df"; + private static final String ERROR_COLOR = "#6e7781"; + + private static final String PRE_STYLE = "margin:0 0 1em 0;padding:4px 0;border:1px solid #d0d7de;border-radius:6px;background:#ffffff;" + + "color:#1f2328;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px;line-height:1.5;" + + "overflow-x:auto;white-space:pre;tab-size:4"; + private static final String LINE_STYLE = "display:block;min-width:max-content;padding:0 10px"; + + private static final String TAB_STYLE = "background:rgba(140,149,159,0.3)"; + + private final SpotlessReport report; + private final String mainPage; + /** Files that need formatting, have lints, do not converge or could not be checked, in report order. */ + private final List problemFiles = new ArrayList<>(); + private final Map formatOf = new IdentityHashMap<>(); + private final Map pageOf = new IdentityHashMap<>(); + + ReportRenderer(SpotlessReport report, String outputName) { + this.report = report; + this.mainPage = outputName + ".html"; + // lower-cased, because names that differ only in case are the same file + // on case-insensitive file systems, such as the defaults on Windows and macOS + Set usedPages = new HashSet<>(); + usedPages.add(mainPage.toLowerCase(Locale.ROOT)); + for (Format format : report.formats()) { + for (FileResult file : format.files) { + if (!file.isClean()) { + problemFiles.add(file); + formatOf.put(file, format); + pageOf.put(file, uniquePageName(outputName, file.path, usedPages)); + } + } + } + } + + private static String uniquePageName(String outputName, String path, Set usedPages) { + String base = outputName + "-" + path.replace('/', '.').replaceAll("[^A-Za-z0-9._-]", "_"); + if (base.length() > 180) { + // stay well within the file-name limits of common file systems + base = base.substring(0, 180); + } + String name = base + ".html"; + for (int i = 2; !usedPages.add(name.toLowerCase(Locale.ROOT)); i++) { + name = base + "-" + i + ".html"; + } + return name; + } + + /** + * Renders the summary page into {@code mainSink}, then one page per problem file through {@code pages}. + * If {@code pages} is {@code null}, the details of each problem file go on the summary page instead. + */ + void render(Sink mainSink, PageSinks pages) throws IOException { + try { + renderSummaryPage(mainSink, pages != null); + } finally { + mainSink.flush(); + mainSink.close(); + } + if (pages != null) { + for (FileResult file : problemFiles) { + Sink sink = pages.open(pageOf.get(file)); + try { + renderFilePage(sink, file); + } finally { + sink.flush(); + sink.close(); + } + } + } + } + + private void renderSummaryPage(Sink sink, boolean detailsOnOwnPages) { + head(sink, "Spotless"); + sink.body(); + sink.section1(); + title(sink, 1, "Spotless"); + sink.paragraph(); + sink.text("Spotless checks that files match the formatting rules configured for this project. This page covers the files "); + code(sink, "mvn spotless:check"); + sink.text(" looks at: which ones need formatting, with the changes "); + code(sink, "mvn spotless:apply"); + sink.text(" would make, and which ones have lint problems. Generating it does not change any file."); + sink.paragraph_(); + paragraph(sink, verdict()); + if (!report.formats().isEmpty()) { + renderSummaryTable(sink); + if (!problemFiles.isEmpty()) { + renderProblemFiles(sink, detailsOnOwnPages); + renderLintTable(sink, detailsOnOwnPages); + if (!detailsOnOwnPages) { + section(sink, 2); + title(sink, 2, "Details"); + for (FileResult file : problemFiles) { + section(sink, 3); + sink.anchor(anchorOf(file)); + sink.anchor_(); + title(sink, 3, file.path); + describeFormat(sink, formatOf.get(file)); + renderFileDetails(sink, file, 4); + section_(sink, 3); + } + section_(sink, 2); + } + } + } + sink.section1_(); + sink.body_(); + } + + private String verdict() { + if (report.formats().isEmpty()) { + return "No Spotless formats are configured for this report. It uses the plugin-level of spotless-maven-plugin; configuration inside an is not used."; + } + Totals totals = new Totals(); + for (Format format : report.formats()) { + totals.add(format); + } + if (totals.files == 0) { + return "Spotless found no files to look at. If the formats use ratchetFrom, only files that changed since that commit are included."; + } + if (problemFiles.isEmpty()) { + return totals.files == 1 ? "The only file Spotless looked at is clean." : "All " + totals.files + " files Spotless looked at are clean."; + } + List problems = new ArrayList<>(); + if (totals.needFormatting > 0) { + problems.add(totals.needFormatting + (totals.needFormatting == 1 ? " needs" : " need") + " formatting"); + } + if (totals.withLints > 0) { + problems.add(totals.withLints + (totals.withLints == 1 ? " has" : " have") + " lint problems"); + } + if (totals.notConverging > 0) { + problems.add(totals.notConverging + (totals.notConverging == 1 ? " does" : " do") + " not converge"); + } + if (totals.errors > 0) { + problems.add(totals.errors + " could not be checked"); + } + StringBuilder verdict = new StringBuilder("Of the ").append(count(totals.files, "file")).append(" Spotless looked at, "); + for (int i = 0; i < problems.size(); i++) { + if (i > 0) { + verdict.append(i == problems.size() - 1 ? " and " : ", "); + } + verdict.append(problems.get(i)); + } + verdict.append('.'); + if (totals.needFormatting > 0) { + verdict.append(" Run mvn spotless:apply to format them."); + } + return verdict.toString(); + } + + private void renderSummaryTable(Sink sink) { + Totals totals = new Totals(); + for (Format format : report.formats()) { + totals.add(format); + } + boolean showNotConverging = totals.notConverging > 0; + boolean showErrors = totals.errors > 0; + + section(sink, 2); + title(sink, 2, "Summary"); + List headers = new ArrayList<>(List.of("Format", "Steps", "Files", "Clean", "Need formatting", "Have lint problems")); + if (showNotConverging) { + headers.add("Do not converge"); + } + if (showErrors) { + headers.add("Could not be checked"); + } + headers.add("Overview"); + int[] justification = new int[headers.size()]; + for (int i = 0; i < justification.length; i++) { + justification[i] = i >= 2 && i < headers.size() - 1 ? Sink.JUSTIFY_RIGHT : Sink.JUSTIFY_LEFT; + } + sink.table(); + sink.tableRows(justification, false); + headerRow(sink, headers); + for (Format format : report.formats()) { + Totals row = new Totals(); + row.add(format); + sink.tableRow(); + sink.tableCell(); + code(sink, format.name); + sink.tableCell_(); + cell(sink, format.steps.isEmpty() ? "none" : String.join(", ", format.steps)); + totalsCells(sink, row, showNotConverging, showErrors); + sink.tableRow_(); + } + if (report.formats().size() > 1) { + sink.tableRow(); + sink.tableCell(); + sink.bold(); + sink.text("Total"); + sink.bold_(); + sink.tableCell_(); + cell(sink, ""); + totalsCells(sink, totals, showNotConverging, showErrors); + sink.tableRow_(); + } + sink.tableRows_(); + sink.table_(); + section_(sink, 2); + } + + private static void totalsCells(Sink sink, Totals totals, boolean showNotConverging, boolean showErrors) { + cell(sink, Integer.toString(totals.files)); + cell(sink, Integer.toString(totals.clean)); + cell(sink, Integer.toString(totals.needFormatting)); + cell(sink, Integer.toString(totals.withLints)); + if (showNotConverging) { + cell(sink, Integer.toString(totals.notConverging)); + } + if (showErrors) { + cell(sink, Integer.toString(totals.errors)); + } + sink.tableCell(); + sink.rawText(bar(totals)); + sink.tableCell_(); + } + + /** A bar showing how the files split into clean, need formatting, lints only, not converging and not checked. */ + private static String bar(Totals totals) { + String title = totals.clean + " clean, " + totals.needFormatting + " need formatting, " + totals.lintsOnly + " with lint problems only, " + + totals.notConverging + " not converging, " + totals.errors + " not checked"; + StringBuilder bar = new StringBuilder("

    "); + if (totals.files > 0) { + segment(bar, totals.clean, totals.files, CLEAN_COLOR); + segment(bar, totals.needFormatting, totals.files, FORMATTING_COLOR); + segment(bar, totals.lintsOnly, totals.files, LINT_COLOR); + segment(bar, totals.notConverging, totals.files, NOT_CONVERGING_COLOR); + segment(bar, totals.errors, totals.files, ERROR_COLOR); + } + return bar.append("
    ").toString(); + } + + private static void segment(StringBuilder bar, int part, int whole, String color) { + if (part > 0) { + double percent = 100.0 * part / whole; + bar.append("
    "); + } + } + + private void renderProblemFiles(Sink sink, boolean detailsOnOwnPages) { + section(sink, 2); + title(sink, 2, "Files with problems"); + sink.table(); + sink.tableRows(new int[]{Sink.JUSTIFY_LEFT, Sink.JUSTIFY_LEFT, Sink.JUSTIFY_LEFT, Sink.JUSTIFY_RIGHT}, false); + headerRow(sink, List.of("File", "Format", "Formatting", "Lint problems")); + for (FileResult file : problemFiles) { + sink.tableRow(); + sink.tableCell(); + sink.link(linkTo(file, detailsOnOwnPages)); + code(sink, file.path); + sink.link_(); + sink.tableCell_(); + cell(sink, formatOf.get(file).name); + cell(sink, formattingStatus(file)); + cell(sink, file.lints.isEmpty() ? "" : Integer.toString(file.lints.size())); + sink.tableRow_(); + } + sink.tableRows_(); + sink.table_(); + section_(sink, 2); + } + + /** Lints are computed on the formatted text, so their line numbers differ from the file on disk only when the diff is not empty. */ + private static boolean linesMove(FileResult file) { + return file.changes != null && file.changes.diff != null; + } + + private static String formattingStatus(FileResult file) { + if (file.error != null) { + return "could not be checked"; + } else if (file.didNotConverge) { + return "does not converge"; + } else if (file.changes == null) { + return "no changes"; + } else if (file.changes.diff == null) { + return "invisible changes only"; + } else { + return "+" + file.changes.diff.added() + " -" + file.changes.diff.removed() + " lines"; + } + } + + private void renderLintTable(Sink sink, boolean detailsOnOwnPages) { + boolean anyLints = false; + boolean anyLintsInFilesThatChange = false; + for (FileResult file : problemFiles) { + anyLints |= !file.lints.isEmpty(); + anyLintsInFilesThatChange |= !file.lints.isEmpty() && linesMove(file); + } + if (!anyLints) { + return; + } + section(sink, 2); + title(sink, 2, "Lint problems"); + if (anyLintsInFilesThatChange) { + paragraph(sink, "In files that need formatting, the line numbers refer to the file after mvn spotless:apply has formatted it."); + } + sink.table(); + sink.tableRows(new int[]{Sink.JUSTIFY_LEFT, Sink.JUSTIFY_RIGHT, Sink.JUSTIFY_LEFT, Sink.JUSTIFY_LEFT, Sink.JUSTIFY_LEFT}, false); + headerRow(sink, List.of("File", "Line", "Step", "Code", "Message")); + for (FileResult file : problemFiles) { + for (LintRow lint : file.lints) { + sink.tableRow(); + sink.tableCell(); + sink.link(linkTo(file, detailsOnOwnPages)); + sink.text(file.path); + sink.link_(); + sink.tableCell_(); + cell(sink, lint.lines()); + cell(sink, lint.step); + sink.tableCell(); + code(sink, lint.code); + sink.tableCell_(); + cell(sink, lint.firstLineOfDetail()); + sink.tableRow_(); + } + } + sink.tableRows_(); + sink.table_(); + section_(sink, 2); + } + + private void renderFilePage(Sink sink, FileResult file) { + // Doxia 1 copies the title into the page unescaped, so keep markup out of it; the heading below shows the exact path + head(sink, "Spotless: " + file.path.replaceAll("[<>&\"]", "_")); + sink.body(); + sink.section1(); + title(sink, 1, file.path); + describeFormat(sink, formatOf.get(file)); + sink.paragraph(); + sink.link(mainPage); + sink.text("Back to the Spotless report"); + sink.link_(); + sink.paragraph_(); + renderFileDetails(sink, file, 2); + sink.section1_(); + sink.body_(); + } + + private static void describeFormat(Sink sink, Format format) { + sink.paragraph(); + sink.text("Format "); + code(sink, format.name); + sink.text(format.steps.isEmpty() ? ", no steps, encoding " : ", steps " + String.join(", ", format.steps) + ", encoding "); + code(sink, format.encoding.name()); + sink.text("."); + sink.paragraph_(); + } + + private void renderFileDetails(Sink sink, FileResult file, int level) { + if (file.error != null) { + section(sink, level); + title(sink, level, "Could not be checked"); + paragraph(sink, "Spotless could not check this file:"); + sink.rawText(pre(file.error)); + section_(sink, level); + } + if (file.didNotConverge) { + section(sink, level); + title(sink, level, "Formatting does not converge"); + sink.paragraph(); + sink.text("Applying the formatting steps to this file again and again keeps changing it, so spotless:check and spotless:apply leave the file alone. See "); + sink.link(PADDED_CELL_URL); + sink.text("how Spotless handles formatters that misbehave"); + sink.link_(); + sink.text("."); + sink.paragraph_(); + section_(sink, level); + } + Changes changes = file.changes; + if (changes != null) { + section(sink, level); + title(sink, level, "Changes"); + if (changes.note != null) { + paragraph(sink, changes.note); + } + if (changes.diff != null) { + sink.paragraph(); + sink.text("Running "); + code(sink, "mvn spotless:apply"); + sink.text(" makes these changes:"); + sink.paragraph_(); + sink.rawText(diffHtml(changes.diff)); + int hidden = changes.diff.totalLines() - changes.diff.lines().size(); + if (hidden > 0) { + paragraph(sink, count(hidden, "more line") + " of the diff " + (hidden == 1 ? "is" : "are") + " not shown. Raise the report's maxDiffLines parameter to see more."); + } + } + section_(sink, level); + } + if (!file.lints.isEmpty()) { + section(sink, level); + title(sink, level, "Lint problems"); + if (linesMove(file)) { + paragraph(sink, "The line numbers refer to the file after mvn spotless:apply has formatted it, the + side of the diff above."); + } + sink.table(); + sink.tableRows(new int[]{Sink.JUSTIFY_RIGHT, Sink.JUSTIFY_LEFT, Sink.JUSTIFY_LEFT, Sink.JUSTIFY_LEFT}, false); + headerRow(sink, List.of("Line", "Step", "Code", "Message")); + for (LintRow lint : file.lints) { + sink.tableRow(); + cell(sink, lint.lines()); + cell(sink, lint.step); + sink.tableCell(); + code(sink, lint.code); + sink.tableCell_(); + sink.tableCell(); + sink.text(lint.firstLineOfDetail()); + if (!lint.firstLineOfDetail().equals(lint.detail)) { + // multi-line details, such as stack traces, stay folded until clicked + sink.rawText("
    Details" + pre(lint.detail) + "
    "); + } + sink.tableCell_(); + sink.tableRow_(); + } + sink.tableRows_(); + sink.table_(); + section_(sink, level); + } + } + + private static String diffHtml(UnifiedDiff diff) { + StringBuilder html = new StringBuilder("
    ");
    +		for (UnifiedDiff.Line line : diff.lines()) {
    +			html.append("");
    +			if (line.kind == UnifiedDiff.Kind.ADDED || line.kind == UnifiedDiff.Kind.REMOVED) {
    +				appendWithVisibleWhitespace(html, line.text, line.kind == UnifiedDiff.Kind.ADDED ? "rgba(46,160,67,0.45)" : "rgba(207,34,46,0.45)");
    +			} else {
    +				html.append(Html.escape(line.text));
    +			}
    +			html.append("");
    +		}
    +		return html.append("
    ").toString(); + } + + private static String styleFor(UnifiedDiff.Kind kind) { + switch (kind) { + case HUNK: + return ";background:#ddf4ff;color:#57606a"; + case ADDED: + return ";background:#e6ffec"; + case REMOVED: + return ";background:#ffebe9"; + case NOTE: + return ";color:#57606a;font-style:italic"; + default: + return ""; + } + } + + /** + * Whitespace changes are invisible in a plain diff, so in changed lines each tab gets a gray background and + * trailing whitespace a darker version of the line's color. A change from tabs to spaces then shows up, like the + * middle-dot and {@code \t} markers in the message of {@code spotless:check}. + */ + private static void appendWithVisibleWhitespace(StringBuilder html, String text, String trailingColor) { + int end = text.length(); + while (end > 1 && (text.charAt(end - 1) == ' ' || text.charAt(end - 1) == '\t')) { + end--; + } + String[] betweenTabs = text.substring(0, end).split("\t", -1); + for (int i = 0; i < betweenTabs.length; i++) { + if (i > 0) { + html.append("\t"); + } + html.append(Html.escape(betweenTabs[i])); + } + if (end < text.length()) { + html.append("").append(Html.escape(text.substring(end))).append(""); + } + } + + private static String pre(String text) { + return "
    " + Html.escape(text) + "
    "; + } + + private String linkTo(FileResult file, boolean detailsOnOwnPages) { + return detailsOnOwnPages ? pageOf.get(file) : "#" + anchorOf(file); + } + + private String anchorOf(FileResult file) { + String page = pageOf.get(file); + return "file-" + page.substring(0, page.length() - ".html".length()); + } + + private static void head(Sink sink, String title) { + sink.head(); + sink.title(); + sink.text(title); + sink.title_(); + sink.head_(); + } + + private static void section(Sink sink, int level) { + switch (level) { + case 1: + sink.section1(); + break; + case 2: + sink.section2(); + break; + case 3: + sink.section3(); + break; + default: + sink.section4(); + break; + } + } + + private static void section_(Sink sink, int level) { + switch (level) { + case 1: + sink.section1_(); + break; + case 2: + sink.section2_(); + break; + case 3: + sink.section3_(); + break; + default: + sink.section4_(); + break; + } + } + + private static void title(Sink sink, int level, String text) { + switch (level) { + case 1: + sink.sectionTitle1(); + sink.text(text); + sink.sectionTitle1_(); + break; + case 2: + sink.sectionTitle2(); + sink.text(text); + sink.sectionTitle2_(); + break; + case 3: + sink.sectionTitle3(); + sink.text(text); + sink.sectionTitle3_(); + break; + default: + sink.sectionTitle4(); + sink.text(text); + sink.sectionTitle4_(); + break; + } + } + + private static void paragraph(Sink sink, String text) { + sink.paragraph(); + sink.text(text); + sink.paragraph_(); + } + + private static void code(Sink sink, String text) { + sink.monospaced(); + sink.text(text); + sink.monospaced_(); + } + + private static void cell(Sink sink, String text) { + sink.tableCell(); + sink.text(text); + sink.tableCell_(); + } + + private static void headerRow(Sink sink, List headers) { + sink.tableRow(); + for (String header : headers) { + sink.tableHeaderCell(); + sink.text(header); + sink.tableHeaderCell_(); + } + sink.tableRow_(); + } + + /** File counts for one format, or for all of them. Every file is counted in exactly one of the last five buckets. */ + private static final class Totals { + int files; + int withLints; + int clean; + int needFormatting; + int lintsOnly; + int notConverging; + int errors; + + void add(Format format) { + for (FileResult file : format.files) { + files++; + withLints += file.lints.isEmpty() ? 0 : 1; + if (file.error != null) { + errors++; + } else if (file.didNotConverge) { + notConverging++; + } else if (file.changes != null) { + needFormatting++; + } else if (!file.lints.isEmpty()) { + lintsOnly++; + } else { + clean++; + } + } + } + } +} diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/SpotlessReport.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/SpotlessReport.java new file mode 100644 index 0000000000..8b5e0b7b42 --- /dev/null +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/SpotlessReport.java @@ -0,0 +1,320 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.maven.report; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.maven.doxia.sink.Sink; +import org.apache.maven.doxia.sink.SinkFactory; + +import com.diffplug.spotless.DirtyState; +import com.diffplug.spotless.Formatter; +import com.diffplug.spotless.FormatterStep; +import com.diffplug.spotless.LineEnding; +import com.diffplug.spotless.Lint; +import com.diffplug.spotless.LintState; +import com.diffplug.spotless.generic.FenceStep; + +/** + * What Spotless found in a project, collected one format at a time, and rendered as Maven site pages: + * a summary page plus one page for each file that needs formatting, has lint problems, does not converge or could + * not be checked. + */ +public final class SpotlessReport { + private final int maxDiffLines; + private final List formats = new ArrayList<>(); + private final Set formatNames = new HashSet<>(); + + /** @param maxDiffLines the most lines of diff kept for each file; {@code 0} or less keeps whole diffs */ + public SpotlessReport(int maxDiffLines) { + this.maxDiffLines = maxDiffLines; + } + + /** + * Starts collecting results for one format, such as {@code }. + * + * @param factoryName the simple class name of the format's factory, e.g. {@code Java} or {@code Format} + */ + public Format addFormat(String factoryName, Formatter formatter) { + String base = factoryName.isEmpty() ? "format" : Character.toLowerCase(factoryName.charAt(0)) + factoryName.substring(1); + String name = base; + for (int i = 2; formatNames.contains(name); i++) { + name = base + " #" + i; + } + formatNames.add(name); + List steps = new ArrayList<>(); + for (FormatterStep step : formatter.getSteps()) { + steps.add(step.getName()); + } + if (steps.size() == 1 && steps.get(0).equals(FenceStep.defaultToggleName())) { + // wraps all the steps in one fence step, which hides their names + steps.set(0, FenceStep.defaultToggleName() + " (spotless:off and spotless:on around the configured steps)"); + } + Format format = new Format(name, steps, formatter.getEncoding(), maxDiffLines); + formats.add(format); + return format; + } + + List formats() { + return Collections.unmodifiableList(formats); + } + + /** A one-line summary for the build log, e.g. {@code Spotless report: 3 files, 1 needs formatting.} */ + public String summary() { + int files = 0; + int needFormatting = 0; + int withLints = 0; + int notConverging = 0; + int errors = 0; + for (Format format : formats) { + for (FileResult file : format.files) { + files++; + needFormatting += file.changes != null ? 1 : 0; + withLints += file.lints.isEmpty() ? 0 : 1; + notConverging += file.didNotConverge ? 1 : 0; + errors += file.error != null ? 1 : 0; + } + } + StringBuilder summary = new StringBuilder("Spotless report: ").append(count(files, "file")); + if (needFormatting + withLints + notConverging + errors == 0) { + return summary.append(files == 0 ? "." : ", all clean.").toString(); + } + if (needFormatting > 0) { + summary.append(", ").append(needFormatting).append(needFormatting == 1 ? " needs" : " need").append(" formatting"); + } + if (withLints > 0) { + summary.append(", ").append(withLints).append(withLints == 1 ? " has" : " have").append(" lint problems"); + } + if (notConverging > 0) { + summary.append(", ").append(notConverging).append(notConverging == 1 ? " does" : " do").append(" not converge"); + } + if (errors > 0) { + summary.append(", ").append(errors).append(" could not be checked"); + } + return summary.append('.').toString(); + } + + static String count(int n, String noun) { + return n + " " + noun + (n == 1 ? "" : "s"); + } + + /** + * Renders the report for {@code mvn site}. + * + * @param mainSink the sink for the summary page, named {@code outputName + ".html"} + * @param sinkFactory creates the per-file pages next to the summary page; if {@code null}, the details go on the summary page + * @param outputDirectory the directory {@code sinkFactory} writes pages to + */ + public void render(Sink mainSink, SinkFactory sinkFactory, File outputDirectory, String outputName) throws IOException { + ReportRenderer.PageSinks pages = sinkFactory == null ? null : fileName -> sinkFactory.createSink(outputDirectory, fileName); + new ReportRenderer(this, outputName).render(mainSink, pages); + } + + /** + * Writes the report as self-contained HTML pages, for {@code mvn spotless:report} outside of {@code mvn site}. + * + * @return the summary page + */ + public File writeStandalone(File outputDirectory, String outputName) throws IOException { + Path directory = outputDirectory.toPath(); + Files.createDirectories(directory); + ReportRenderer.PageSinks pages = fileName -> HtmlSink.create(Files.newBufferedWriter(directory.resolve(fileName), StandardCharsets.UTF_8)); + String mainPage = outputName + ".html"; + try { + new ReportRenderer(this, outputName).render(pages.open(mainPage), pages); + } catch (UncheckedIOException e) { + // HtmlSink can only report write failures unchecked + throw e.getCause(); + } + return directory.resolve(mainPage).toFile(); + } + + /** The files of one format, such as {@code }. */ + public static final class Format { + final String name; + final List steps; + final Charset encoding; + final List files = new ArrayList<>(); + private final int maxDiffLines; + + private Format(String name, List steps, Charset encoding, int maxDiffLines) { + this.name = name; + this.steps = List.copyOf(steps); + this.encoding = encoding; + this.maxDiffLines = maxDiffLines; + } + + /** + * Records a file that Spotless checked. + * + * @param path the file's path relative to the project directory, with {@code /} separators + * @param rawBytes the file's content when {@code lintState} was computed + */ + public void addFile(String path, LintState lintState, byte[] rawBytes, Formatter formatter) throws IOException { + DirtyState dirty = lintState.getDirtyState(); + Changes changes = null; + if (!dirty.isClean() && !dirty.didNotConverge()) { + ByteArrayOutputStream canonical = new ByteArrayOutputStream(); + dirty.writeCanonicalTo(canonical); + Charset charset = formatter.getEncoding(); + changes = Changes.between(new String(rawBytes, charset), new String(canonical.toByteArray(), charset), maxDiffLines); + } + List lints = new ArrayList<>(); + if (lintState.isHasLints()) { + for (Map.Entry> entry : lintState.getLintsByStep(formatter).entrySet()) { + for (Lint lint : entry.getValue()) { + lints.add(new LintRow(entry.getKey(), lint.getLineStart(), lint.getLineEnd(), lint.getShortCode(), lint.getDetail())); + } + } + } + files.add(new FileResult(path, changes, lints, dirty.didNotConverge(), null)); + } + + /** Records a file that Spotless could not check, for example because it does not decode in the format's encoding. */ + public void addError(String path, Throwable error) { + String message = error.getMessage() == null ? error.getClass().getName() : error.getMessage(); + files.add(new FileResult(path, null, List.of(), false, message)); + } + } + + /** What Spotless found in one file. */ + static final class FileResult { + final String path; + /** {@code null} if the file is already formatted. */ + final Changes changes; + final List lints; + final boolean didNotConverge; + /** {@code null} unless the file could not be checked. */ + final String error; + + FileResult(String path, Changes changes, List lints, boolean didNotConverge, String error) { + this.path = path; + this.changes = changes; + this.lints = List.copyOf(lints); + this.didNotConverge = didNotConverge; + this.error = error; + } + + boolean isClean() { + return changes == null && lints.isEmpty() && !didNotConverge && error == null; + } + } + + /** One lint problem, as shown in the tables. */ + static final class LintRow { + final String step; + final int lineStart; + final int lineEnd; + final String code; + final String detail; + + LintRow(String step, int lineStart, int lineEnd, String code, String detail) { + this.step = step; + this.lineStart = lineStart; + this.lineEnd = lineEnd; + this.code = code; + this.detail = detail; + } + + String lines() { + if (lineStart == Lint.LINE_UNDEFINED) { + return ""; + } + return lineStart == lineEnd ? Integer.toString(lineStart) : lineStart + "-" + lineEnd; + } + + String firstLineOfDetail() { + int newline = detail.indexOf('\n'); + return newline == -1 ? detail : detail.substring(0, newline); + } + } + + /** The changes {@code spotless:apply} would make to one file. */ + static final class Changes { + /** A sentence about invisible changes such as line endings, or {@code null}. */ + final String note; + /** {@code null} when only invisible characters change. */ + final UnifiedDiff diff; + + private Changes(String note, UnifiedDiff diff) { + this.note = note; + this.diff = diff; + } + + static Changes between(String raw, String formatted, int maxDiffLines) { + String rawUnix = LineEnding.toUnix(raw); + String formattedUnix = LineEnding.toUnix(formatted); + String actual = lineEndings(raw); + String expected = lineEndings(formatted); + // adding or removing the only line break shows up in the diff, it isn't a change of line endings + boolean lineEndingsChange = !actual.equals(expected) && !actual.equals(NO_LINE_BREAKS) && !expected.equals(NO_LINE_BREAKS); + if (rawUnix.equals(formattedUnix)) { + if (lineEndingsChange) { + return new Changes("Only the line endings change: the file uses " + actual + ", but Spotless expects " + expected + ".", null); + } + return new Changes("Only invisible characters change, for example the encoding of some characters.", null); + } + String note = lineEndingsChange ? "The line endings also change: the file uses " + actual + ", but Spotless expects " + expected + "." : null; + return new Changes(note, UnifiedDiff.compute(rawUnix, formattedUnix, maxDiffLines)); + } + + static String lineEndings(String text) { + boolean crlf = false; + boolean lf = false; + boolean cr = false; + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + if (c == '\r') { + if (i + 1 < text.length() && text.charAt(i + 1) == '\n') { + crlf = true; + i++; + } else { + cr = true; + } + } else if (c == '\n') { + lf = true; + } + } + int kinds = (crlf ? 1 : 0) + (lf ? 1 : 0) + (cr ? 1 : 0); + if (kinds > 1) { + return "mixed line endings"; + } else if (crlf) { + return "CRLF (\\r\\n)"; + } else if (cr) { + return "CR (\\r)"; + } else if (lf) { + return "LF (\\n)"; + } else { + return NO_LINE_BREAKS; + } + } + + private static final String NO_LINE_BREAKS = "no line breaks"; + } +} diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/UnifiedDiff.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/UnifiedDiff.java new file mode 100644 index 0000000000..35be68a23a --- /dev/null +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/report/UnifiedDiff.java @@ -0,0 +1,146 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.maven.report; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.eclipse.jgit.diff.DiffFormatter; +import org.eclipse.jgit.diff.EditList; +import org.eclipse.jgit.diff.MyersDiff; +import org.eclipse.jgit.diff.RawText; +import org.eclipse.jgit.diff.RawTextComparator; + +/** + * A git-style unified diff with three lines of context, computed with the same JGit diff that + * {@code spotless:check} uses for its error message. Keeps at most a given number of lines, but counts all of them. + */ +final class UnifiedDiff { + enum Kind { + /** {@code @@ -1,3 +1,3 @@} */ + HUNK, + /** A line that is the same before and after. */ + CONTEXT, + /** A line that only the after text has. */ + ADDED, + /** A line that only the before text has. */ + REMOVED, + /** {@code \ No newline at end of file} */ + NOTE + } + + /** One line of the diff, including its leading {@code ' '}, {@code '+'}, {@code '-'}, {@code '@'} or {@code '\'}. */ + static final class Line { + final Kind kind; + final String text; + + Line(Kind kind, String text) { + this.kind = kind; + this.text = text; + } + } + + private final List lines; + private final int totalLines; + private final int added; + private final int removed; + + private UnifiedDiff(List lines, int totalLines, int added, int removed) { + this.lines = Collections.unmodifiableList(lines); + this.totalLines = totalLines; + this.added = added; + this.removed = removed; + } + + /** + * Diffs two texts that use only {@code \n} line endings. + * + * @param maxLines how many lines of the diff to keep; {@code 0} or less keeps them all + */ + static UnifiedDiff compute(String before, String after, int maxLines) { + RawText a = new RawText(before.getBytes(StandardCharsets.UTF_8)); + RawText b = new RawText(after.getBytes(StandardCharsets.UTF_8)); + EditList edits = new EditList(); + edits.addAll(MyersDiff.INSTANCE.diff(RawTextComparator.DEFAULT, a, b)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (DiffFormatter formatter = new DiffFormatter(out)) { + formatter.format(edits, a, b); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return parse(new String(out.toByteArray(), StandardCharsets.UTF_8), maxLines); + } + + static UnifiedDiff parse(String unified, int maxLines) { + List lines = new ArrayList<>(); + int total = 0; + int added = 0; + int removed = 0; + for (String text : unified.split("\n")) { + if (text.isEmpty()) { + continue; + } + Kind kind; + switch (text.charAt(0)) { + case '@': + kind = Kind.HUNK; + break; + case '+': + kind = Kind.ADDED; + added++; + break; + case '-': + kind = Kind.REMOVED; + removed++; + break; + case '\\': + kind = Kind.NOTE; + break; + default: + kind = Kind.CONTEXT; + break; + } + total++; + if (maxLines <= 0 || lines.size() < maxLines) { + lines.add(new Line(kind, text)); + } + } + return new UnifiedDiff(lines, total, added, removed); + } + + /** The lines that were kept, at most {@code maxLines}. */ + List lines() { + return lines; + } + + /** How many lines the whole diff has, including the ones that were not kept. */ + int totalLines() { + return totalLines; + } + + int added() { + return added; + } + + int removed() { + return removed; + } +} diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java index bcc5791a5b..c893dfe385 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java @@ -68,6 +68,7 @@ public class MavenIntegrationHarness extends ResourceHarness { private static final String MODULES = "modules"; private static final String DEPENDENCIES = "dependencies"; private static final String PLUGINS = "plugins"; + private static final String REPORTING = "reporting"; private static final String MODULE_NAME = "name"; private static final int REMOTE_DEBUG_PORT = 5005; @@ -223,6 +224,13 @@ protected void writePom(String[] executions, String[] configuration, String[] de setFile("pom.xml").toContent(pomXmlContent); } + /** Writes a pom with the given {@code } section, for testing {@code spotless:report} through {@code mvn site}. */ + protected void writePomWithReporting(String[] plugins, String[] configuration, String reporting) throws IOException { + Map params = buildPomXmlParams(null, null, null, configuration, null, null, plugins); + params.put(REPORTING, reporting); + setFile("pom.xml").toContent(createPomXmlContent(POM_TEMPLATE, params)); + } + protected MavenRunner mavenRunner() throws IOException { MavenRunner mavenRunner = MavenRunner.create() .withProjectDir(rootFolder()) diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpotlessReportMojoTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpotlessReportMojoTest.java new file mode 100644 index 0000000000..690cb2fb60 --- /dev/null +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpotlessReportMojoTest.java @@ -0,0 +1,150 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.maven; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.file.Files; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class SpotlessReportMojoTest extends MavenIntegrationHarness { + private static final String CLEAN = "class Clean {}\n"; + private static final String DIRTY = "class Dirty {} "; + private static final String MAVEN_3_9 = "distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip\n"; + private static final String[] STEPS = {"", ""}; + + @Test + void reportShowsFilesThatNeedFormattingWithoutChangingThem() throws Exception { + writePomWithFormatSteps(STEPS); + setFile("src/main/java/Clean.java").toContent(CLEAN); + setFile("src/main/java/Dirty.java").toContent(DIRTY); + + String output = mavenRunner().withArguments("spotless:report").runNoError().stdOutUtf8(); + + assertThat(output).contains("Spotless report: 2 files, 1 needs formatting."); + assertFile("src/main/java/Dirty.java").hasContent(DIRTY); + assertThat(read("target/site/spotless.html")).contains("src/main/java/Dirty.java").contains("1 needs formatting"); + assertThat(read("target/site/spotless-src.main.java.Dirty.java.html")).contains("+class Dirty {}"); + } + + @Test + void reportLeavesTheUpToDateIndexAlone() throws Exception { + writePomWithFormatSteps(STEPS); + setFile("src/main/java/Clean.java").toContent(CLEAN); + mavenRunner().withArguments("spotless:apply").runNoError(); + byte[] index = Files.readAllBytes(newFile("target/spotless-index").toPath()); + setFile("src/main/java/Dirty.java").toContent(DIRTY); + + String output = mavenRunner().withArguments("spotless:report").runNoError().stdOutUtf8(); + + // Clean.java is in the index, but the report still looks at it + assertThat(output).contains("Spotless report: 2 files, 1 needs formatting."); + assertThat(Files.readAllBytes(newFile("target/spotless-index").toPath())).isEqualTo(index); + } + + @ParameterizedTest + @ValueSource(strings = {"spotless.report.skip", "spotless.skip"}) + void reportCanBeSkipped(String property) throws Exception { + writePomWithFormatSteps(STEPS); + setFile("src/main/java/Dirty.java").toContent(DIRTY); + + String output = mavenRunner().withArguments("spotless:report", "-D" + property + "=true").runNoError().stdOutUtf8(); + + assertThat(output).contains("Spotless report skipped"); + assertThat(newFile("target/site/spotless.html")).doesNotExist(); + } + + @Test + void siteWithMavenSitePlugin3_12_UsesDoxia1() throws Exception { + writePomForSite("3.12.1", new String[0], ""); + setFile("src/main/java/Dirty.java").toContent(DIRTY); + + mavenRunner().withArguments("site").runNoError(); + + assertSiteHasSpotlessReport(); + } + + @Test + void siteWithMavenSitePlugin3_21_UsesDoxia2() throws Exception { + // maven-site-plugin 3.20 and later need Maven 3.6.3 or later + setFile(".mvn/wrapper/maven-wrapper.properties").toContent(MAVEN_3_9); + writePomForSite("3.21.0", new String[0], ""); + setFile("src/main/java/Dirty.java").toContent(DIRTY); + + mavenRunner().withArguments("site").runNoError(); + + assertSiteHasSpotlessReport(); + } + + @Test + void siteReportTakesBuildConfigurationButPrefersReporting() throws Exception { + setFile(".mvn/wrapper/maven-wrapper.properties").toContent(MAVEN_3_9); + writePomForSite("3.21.0", + // the site owns the output directory, and wins over + new String[]{"${project.build.directory}/elsewhere", "1"}, + "2"); + setFile("src/main/java/Dirty.java").toContent(DIRTY); + + mavenRunner().withArguments("site").runNoError(); + + // the diff has 4 lines: the hunk header, the removed line, "\ No newline at end of file" and the added line + assertThat(read("target/site/spotless-src.main.java.Dirty.java.html")).contains("2 more lines of the diff are not shown."); + assertThat(newFile("target/elsewhere")).doesNotExist(); + } + + @Test + void skipInBuildConfigurationSkipsTheSiteReport() throws Exception { + writePomForSite("3.12.1", new String[]{"true"}, ""); + setFile("src/main/java/Dirty.java").toContent(DIRTY); + + mavenRunner().withArguments("site").runNoError(); + + assertThat(newFile("target/site/spotless.html")).doesNotExist(); + } + + /** + * @param buildConfiguration extra plugin-level configuration in {@code }, next to the formats + * @param reportingConfiguration XML inside the {@code } entry for the plugin, which has no version: it takes the one from {@code } + */ + private void writePomForSite(String sitePluginVersion, String[] buildConfiguration, String reportingConfiguration) throws IOException { + String[] formats = formats(groupWithSteps("format", including("src/**/java/**/*.java"), STEPS)); + String[] configuration = new String[formats.length + buildConfiguration.length]; + System.arraycopy(formats, 0, configuration, 0, formats.length); + System.arraycopy(buildConfiguration, 0, configuration, formats.length, buildConfiguration.length); + writePomWithReporting( + new String[]{ + "", + " org.apache.maven.plugins", + " maven-site-plugin", + " " + sitePluginVersion + "", + ""}, + configuration, + // excludeDefaults: otherwise the site plugin adds the latest maven-project-info-reports-plugin, which may not suit the Maven version under test + "truecom.diffplug.spotlessspotless-maven-plugin" + + reportingConfiguration + ""); + } + + private void assertSiteHasSpotlessReport() throws IOException { + assertThat(read("target/site/spotless.html")).contains("src/main/java/Dirty.java").contains("1 needs formatting"); + assertThat(read("target/site/spotless-src.main.java.Dirty.java.html")).contains("+class Dirty {}"); + assertThat(read("target/site/project-reports.html")).contains("Spotless"); + assertFile("src/main/java/Dirty.java").hasContent(DIRTY); + } +} diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/report/SpotlessReportTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/report/SpotlessReportTest.java new file mode 100644 index 0000000000..fba6ef5d53 --- /dev/null +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/report/SpotlessReportTest.java @@ -0,0 +1,304 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.maven.report; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import com.diffplug.spotless.Formatter; +import com.diffplug.spotless.FormatterStep; +import com.diffplug.spotless.LineEnding; +import com.diffplug.spotless.Lint; +import com.diffplug.spotless.LintState; +import com.diffplug.spotless.NeverUpToDateStep; +import com.diffplug.spotless.generic.TrimTrailingWhitespaceStep; + +class SpotlessReportTest { + @TempDir + File dir; + + private SpotlessReport report = new SpotlessReport(1000); + + @Test + void cleanProject() throws IOException { + Formatter formatter = formatter(LineEnding.UNIX, TrimTrailingWhitespaceStep.create()); + add(report.addFormat("Java", formatter), formatter, "src/A.java", "class A {}\n"); + + String summary = writeStandalone(); + assertThat(summary).contains("The only file Spotless looked at is clean.").contains("java").contains("trimTrailingWhitespace"); + assertThat(new File(dir, "site").list()).containsExactly("spotless.html"); + assertThat(report.summary()).isEqualTo("Spotless report: 1 file, all clean."); + } + + @Test + void fileThatNeedsFormattingGetsItsOwnPageWithADiff() throws IOException { + Formatter formatter = formatter(LineEnding.UNIX, TrimTrailingWhitespaceStep.create()); + SpotlessReport.Format format = report.addFormat("Java", formatter); + add(format, formatter, "src/Clean.java", "class Clean {}\n"); + add(format, formatter, "src/Dirty.java", "class Dirty {} \n"); + + String summary = writeStandalone(); + assertThat(summary) + .contains("Of the 2 files Spotless looked at, 1 needs formatting. Run mvn spotless:apply to format them.") + .contains("
    src/Dirty.java") + .contains("+1 -1 lines") + .doesNotContain("src/Clean.java"); + String page = read("site/spotless-src.Dirty.java.html"); + assertThat(page) + .contains("

    src/Dirty.java

    ") + .contains("Back to the Spotless report") + .contains("@@ -1 +1 @@") + // trailing whitespace is highlighted, because it's invisible otherwise + .contains("-class Dirty {} ") + .contains("+class Dirty {}"); + assertThat(report.summary()).isEqualTo("Spotless report: 2 files, 1 needs formatting."); + } + + @Test + void tabsInChangedLinesAreVisible() throws IOException { + FormatterStep tabsToSpaces = NeverUpToDateStep.create("tabsToSpaces", input -> input.replace("\t", " ")); + Formatter formatter = formatter(LineEnding.UNIX, tabsToSpaces); + add(report.addFormat("Java", formatter), formatter, "src/Tabs.java", "class Tabs {\n\tint x;\n}\n"); + + writeStandalone(); + assertThat(read("site/spotless-src.Tabs.java.html")) + .contains("-\tint x;") + .contains("+ int x;"); + } + + @Test + void lintProblemsAreListed() throws IOException { + FormatterStep noTodo = NeverUpToDateStep.create("noTodo", input -> { + if (input.contains("TODO")) { + throw Lint.atLine(2, "todo", "Remove the TODO\nso nobody forgets it").shortcut(); + } + return input; + }); + Formatter formatter = formatter(LineEnding.UNIX, noTodo); + add(report.addFormat("Java", formatter), formatter, "src/Todo.java", "class Todo {\n// TODO\n}\n"); + + String summary = writeStandalone(); + assertThat(summary) + .contains("1 has lint problems") + .contains("

    Lint problems

    ") + .contains("no changes1") + .contains("src/Todo.java2noTodotodoRemove the TODO") + // the file doesn't need formatting, so its line numbers are those of the file on disk + .doesNotContain("line numbers refer to the file after"); + String page = read("site/spotless-src.Todo.java.html"); + assertThat(page) + .contains("2noTodotodoRemove the TODO
    Details") + .contains("so nobody forgets it") + .doesNotContain("

    Changes

    "); + } + + @Test + void lintLineNumbersOfFilesThatNeedFormattingAreExplained() throws IOException { + FormatterStep noTodo = NeverUpToDateStep.create("noTodo", input -> { + if (input.contains("TODO")) { + throw Lint.atLine(1, "todo", "Remove the TODO").shortcut(); + } + return input; + }); + Formatter formatter = formatter(LineEnding.UNIX, TrimTrailingWhitespaceStep.create(), noTodo); + add(report.addFormat("Java", formatter), formatter, "src/Both.java", "// TODO \n"); + + assertThat(writeStandalone()).contains("In files that need formatting, the line numbers refer to the file after mvn spotless:apply has formatted it."); + assertThat(read("site/spotless-src.Both.java.html")).contains("The line numbers refer to the file after mvn spotless:apply has formatted it"); + } + + @Test + void filesThatDoNotConvergeAreExplained() throws IOException { + FormatterStep grow = NeverUpToDateStep.create("grow", input -> input + "x"); + Formatter formatter = formatter(LineEnding.UNIX, grow); + add(report.addFormat("Format", formatter), formatter, "grows.txt", "a\n"); + + assertThat(writeStandalone()).contains("Do not converge").contains("does not converge"); + assertThat(read("site/spotless-grows.txt.html")).contains("PADDEDCELL.md").contains("spotless:check and spotless:apply leave the file alone"); + assertThat(report.summary()).isEqualTo("Spotless report: 1 file, 1 does not converge."); + } + + @Test + void lineEndingChangesAreExplainedInsteadOfDiffed() throws IOException { + Formatter formatter = formatter(LineEnding.WINDOWS); + add(report.addFormat("Format", formatter), formatter, "README.txt", "a\nb\n"); + + assertThat(writeStandalone()).contains("invisible changes only"); + assertThat(read("site/spotless-README.txt.html")) + .contains("Only the line endings change: the file uses LF (\\n), but Spotless expects CRLF (\\r\\n).") + .doesNotContain("alert(1) \n"); + + writeStandalone(); + assertThat(read("site/spotless-src.x.js.html")) + .contains("<script>alert(1)</script>") + .doesNotContain("