diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9ef9b7582b..44a658b464 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,6 @@ concurrency: cancel-in-progress: true jobs: sanityCheck: - name: spotlessCheck assemble testClasses runs-on: ubuntu-latest env: buildcacheuser: ${{ secrets.BUILDCACHE_USER }} @@ -31,6 +30,8 @@ jobs: uses: gradle/actions/setup-gradle@v4 - name: spotlessCheck run: ./gradlew spotlessCheck + - name: rewriteDryRun + run: ./gradlew rewriteDryRun - name: assemble testClasses run: ./gradlew assemble testClasses build: @@ -66,10 +67,10 @@ jobs: uses: gradle/actions/setup-gradle@v4 - name: build (maven-only) if: matrix.kind == 'maven' - run: ./gradlew :plugin-maven:build -x spotlessCheck + run: ./gradlew :plugin-maven:build -x spotlessCheck -x rewriteDryRun - name: build (everything-but-maven) if: matrix.kind == 'gradle' - run: ./gradlew build -x spotlessCheck -PSPOTLESS_EXCLUDE_MAVEN=true + run: ./gradlew build -x spotlessCheck -x rewriteDryRun -PSPOTLESS_EXCLUDE_MAVEN=true - name: test npm if: matrix.kind == 'npm' run: ./gradlew testNpm diff --git a/CHANGES.md b/CHANGES.md index 38b36ca7b4..891199c124 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -27,6 +27,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ### Added * Add a `lint` mode to `ReplaceRegexStep` ([#2571](https://github.com/diffplug/spotless/pull/2571)) * `LintSuppression` now enforces unix-style paths in its `setPath` and `relativizeAsUnix` methods. ([#2629](https://github.com/diffplug/spotless/pull/2629)) +* Add `rewrite` support ([#2588](https://github.com/diffplug/spotless/pull/2588)) ## [3.3.1] - 2025-07-21 ### Fixed diff --git a/build.gradle b/build.gradle index fafd6abe43..042a7c9647 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,7 @@ repositories { apply from: rootProject.file('gradle/java-publish.gradle') apply from: rootProject.file('gradle/changelog.gradle') allprojects { + apply from: rootProject.file('gradle/rewrite.gradle') apply from: rootProject.file('gradle/spotless.gradle') } apply from: rootProject.file('gradle/spotless-freshmark.gradle') @@ -27,3 +28,8 @@ spotless { endWithNewline() } } + +dependencies { + rewrite(platform("org.openrewrite.recipe:rewrite-recipe-bom:3.14.1")) + rewrite("org.openrewrite.recipe:rewrite-migrate-java:3.17.1") +} diff --git a/gradle/java-publish.gradle b/gradle/java-publish.gradle index dad3328f5a..80931905ef 100644 --- a/gradle/java-publish.gradle +++ b/gradle/java-publish.gradle @@ -103,9 +103,9 @@ model { from components.java } - groupId project.group - artifactId project.ext.artifactId - version project.version + groupId = project.group + artifactId = project.ext.artifactId + version = project.version def projectExtArtifactId = project.ext.artifactId def projectDescription = project.description diff --git a/gradle/rewrite.gradle b/gradle/rewrite.gradle new file mode 100644 index 0000000000..f520ab77eb --- /dev/null +++ b/gradle/rewrite.gradle @@ -0,0 +1,7 @@ +apply plugin: 'org.openrewrite.rewrite' + +rewrite { + activeRecipe("org.openrewrite.java.migrate.UpgradeToJava17") + exportDatatables = true + failOnDryRunResults = true +} diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/EclipseBasedStepBuilder.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/EclipseBasedStepBuilder.java index 0dff3f6898..01f78aab23 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/EclipseBasedStepBuilder.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/EclipseBasedStepBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -175,7 +175,7 @@ private static String convertEclipseVersion(String version) { char lastChar = version.charAt(version.length() - 1); if ('.' != lastChar && 'a' <= lastChar) { semanticVersion = version.substring(0, version.length() - 1); - semanticVersion += String.format(".%d", (int) lastChar); + semanticVersion += ".%d".formatted((int) lastChar); } } return semanticVersion; diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/cpp/EclipseCdtFormatterStep.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/cpp/EclipseCdtFormatterStep.java index 9582eeed31..b68cb93bb4 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/cpp/EclipseCdtFormatterStep.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/cpp/EclipseCdtFormatterStep.java @@ -69,7 +69,7 @@ private static FormatterFunc apply(EquoBasedStepBuilder.State state) throws Exce return (String) method.invoke(formatter, input); } catch (InvocationTargetException exceptionWrapper) { Throwable throwable = exceptionWrapper.getTargetException(); - Exception exception = (throwable instanceof Exception) ? (Exception) throwable : null; + Exception exception = (throwable instanceof Exception e) ? e : null; throw (null == exception) ? exceptionWrapper : exception; } }); diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStep.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStep.java index 4ca2b60c03..0daaefcd60 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStep.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStep.java @@ -97,7 +97,7 @@ private static FormatterFunc apply(EquoBasedStepBuilder.State state) throws Exce return (String) method.invoke(formatter, input); } catch (InvocationTargetException exceptionWrapper) { Throwable throwable = exceptionWrapper.getTargetException(); - Exception exception = (throwable instanceof Exception) ? (Exception) throwable : null; + Exception exception = (throwable instanceof Exception e) ? e : null; throw (null == exception) ? exceptionWrapper : exception; } }); diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStep.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStep.java index 441e6df878..b5982dbf64 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStep.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,7 +67,7 @@ private static FormatterFunc applyWithoutFile(String className, EclipseBasedStep return (String) method.invoke(formatter, input); } catch (InvocationTargetException exceptionWrapper) { Throwable throwable = exceptionWrapper.getTargetException(); - Exception exception = (throwable instanceof Exception) ? (Exception) throwable : null; + Exception exception = (throwable instanceof Exception e) ? e : null; throw (null == exception) ? exceptionWrapper : exception; } }; @@ -85,7 +85,7 @@ public String applyWithFile(String unix, File file) throws Exception { return (String) method.invoke(formatter, unix, file.getAbsolutePath()); } catch (InvocationTargetException exceptionWrapper) { Throwable throwable = exceptionWrapper.getTargetException(); - Exception exception = (throwable instanceof Exception) ? (Exception) throwable : null; + Exception exception = (throwable instanceof Exception e) ? e : null; throw (null == exception) ? exceptionWrapper : exception; } } diff --git a/lib/src/main/java/com/diffplug/spotless/ConfigurationCacheHackList.java b/lib/src/main/java/com/diffplug/spotless/ConfigurationCacheHackList.java index 58794fd588..a009c2e51e 100644 --- a/lib/src/main/java/com/diffplug/spotless/ConfigurationCacheHackList.java +++ b/lib/src/main/java/com/diffplug/spotless/ConfigurationCacheHackList.java @@ -16,6 +16,7 @@ package com.diffplug.spotless; import java.io.IOException; +import java.io.Serial; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; @@ -51,6 +52,7 @@ * to make Spotless work with all of Gradle's cache systems at once. */ public class ConfigurationCacheHackList implements java.io.Serializable { + @Serial private static final long serialVersionUID = 6914178791997323870L; private boolean optimizeForEquality; @@ -108,8 +110,8 @@ public void clear() { public void addAll(Collection c) { for (FormatterStep step : c) { - if (step instanceof FormatterStepSerializationRoundtrip) { - var clone = ((FormatterStepSerializationRoundtrip) step).hackClone(optimizeForEquality); + if (step instanceof FormatterStepSerializationRoundtrip roundtrip) { + var clone = roundtrip.hackClone(optimizeForEquality); backingList.add(clone); } else { backingList.add(step); @@ -120,8 +122,8 @@ public void addAll(Collection c) { public List getSteps() { var result = new ArrayList(backingList.size()); for (Object obj : backingList) { - if (obj instanceof FormatterStepSerializationRoundtrip.HackClone) { - result.add(((FormatterStepSerializationRoundtrip.HackClone) obj).rehydrate()); + if (obj instanceof FormatterStepSerializationRoundtrip.HackClone clone) { + result.add(clone.rehydrate()); } else { result.add((FormatterStep) obj); } diff --git a/lib/src/main/java/com/diffplug/spotless/FileSignature.java b/lib/src/main/java/com/diffplug/spotless/FileSignature.java index 0d26d86ff8..9a2ea1c1d8 100644 --- a/lib/src/main/java/com/diffplug/spotless/FileSignature.java +++ b/lib/src/main/java/com/diffplug/spotless/FileSignature.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.Serial; import java.io.Serializable; import java.security.MessageDigest; import java.util.Arrays; @@ -38,6 +39,7 @@ /** Computes a signature for any needed files. */ public final class FileSignature implements Serializable { + @Serial private static final long serialVersionUID = 2L; /* @@ -98,6 +100,7 @@ private FileSignature(final List files) throws IOException { /** A view of `FileSignature` which can be safely roundtripped. */ public static class Promised implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final List files; @SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") @@ -212,6 +215,7 @@ synchronized Sig sign(File fileInput) throws IOException { @SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") private static final class Sig implements Serializable { + @Serial private static final long serialVersionUID = 6727302747168655222L; @SuppressWarnings("unused") diff --git a/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java index bcc444ad57..b64d82f2b5 100644 --- a/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package com.diffplug.spotless; import java.io.File; +import java.io.Serial; import java.util.List; import java.util.Objects; import java.util.regex.Pattern; @@ -73,5 +74,6 @@ public int hashCode() { return Objects.hash(delegateStep, onMatch, contentPattern.pattern()); } + @Serial private static final long serialVersionUID = 2L; } diff --git a/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java index bc5ddf6053..056984e584 100644 --- a/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package com.diffplug.spotless; import java.io.File; +import java.io.Serial; import java.util.List; import java.util.Objects; @@ -69,5 +70,6 @@ public int hashCode() { return Objects.hash(delegateStep, filter); } + @Serial private static final long serialVersionUID = 1L; } diff --git a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java index 43846a2c9e..c511b59997 100644 --- a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java +++ b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2024 DiffPlug + * Copyright 2020-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package com.diffplug.spotless; import java.io.IOException; +import java.io.Serial; import java.io.Serializable; import java.nio.charset.Charset; import java.util.Objects; @@ -33,6 +34,7 @@ * will find grep, confirm that it is version 2.5.7, and then return. */ public class ForeignExe implements Serializable { + @Serial private static final long serialVersionUID = 1L; private @Nullable String pathToExe; private String versionFlag = "--version"; diff --git a/lib/src/main/java/com/diffplug/spotless/Formatter.java b/lib/src/main/java/com/diffplug/spotless/Formatter.java index 0635f8dfe6..1bd8c68d81 100644 --- a/lib/src/main/java/com/diffplug/spotless/Formatter.java +++ b/lib/src/main/java/com/diffplug/spotless/Formatter.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamException; +import java.io.Serial; import java.io.Serializable; import java.nio.charset.Charset; import java.util.ArrayList; @@ -33,6 +34,7 @@ /** Formatter which performs the full formatting. */ public final class Formatter implements Serializable, AutoCloseable { + @Serial private static final long serialVersionUID = 1L; // The name is used for logging purpose. It does not convey any applicative diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java b/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java index 499314ee3d..00233ef0a8 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java @@ -100,10 +100,10 @@ public static FormatterProperties fromXmlContent(final Iterable content) final Properties newSettings = FileParser.XML.executeXmlContent(contentElement); properties.properties.putAll(newSettings); } catch (IOException | IllegalArgumentException exception) { - String message = String.format("Failed to add preferences from XML:%n%s%n", contentElement); + String message = "Failed to add preferences from XML:%n%s%n".formatted(contentElement); final String detailedMessage = exception.getMessage(); if (null != detailedMessage) { - message += String.format(" %s", detailedMessage); + message += " %s".formatted(detailedMessage); } throw new IllegalArgumentException(message, exception); } @@ -129,17 +129,17 @@ public static FormatterProperties merge(Properties... properties) { private void add(final File settingsFile) throws IllegalArgumentException { Objects.requireNonNull(settingsFile); if (!(settingsFile.isFile() && settingsFile.canRead())) { - String msg = String.format("Settings file '%s' does not exist or can not be read.", settingsFile); + String msg = "Settings file '%s' does not exist or can not be read.".formatted(settingsFile); throw new IllegalArgumentException(msg); } try { Properties newSettings = FileParser.parse(settingsFile); properties.putAll(newSettings); } catch (IOException | IllegalArgumentException exception) { - String message = String.format("Failed to add properties from '%s' to formatter settings.", settingsFile); + String message = "Failed to add properties from '%s' to formatter settings.".formatted(settingsFile); String detailedMessage = exception.getMessage(); if (null != detailedMessage) { - message += String.format(" %s", detailedMessage); + message += " %s".formatted(detailedMessage); } throw new IllegalArgumentException(message, exception); } @@ -241,8 +241,7 @@ public static Properties parse(final File file) throws IOException, IllegalArgum return parser.execute(file); } } - String msg = String.format( - "The file name extension '%1$s' is not part of the supported file extensions [%2$s].", + String msg = "The file name extension '%1$s' is not part of the supported file extensions [%2$s].".formatted( fileNameExtension, Arrays.toString(FileParser.values())); throw new IllegalArgumentException(msg); @@ -341,7 +340,7 @@ public static Properties parse(final InputStream is, final Node rootNode) return parser.execute(is, rootNode); } } - String msg = String.format("The XML root node '%1$s' is not part of the supported root nodes [%2$s].", + String msg = "The XML root node '%1$s' is not part of the supported root nodes [%2$s].".formatted( rootNodeName, Arrays.toString(XmlParser.values())); throw new IllegalArgumentException(msg); } diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterStepEqualityOnStateSerialization.java b/lib/src/main/java/com/diffplug/spotless/FormatterStepEqualityOnStateSerialization.java index e42e0cb4f9..a14f204458 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatterStepEqualityOnStateSerialization.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatterStepEqualityOnStateSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package com.diffplug.spotless; import java.io.File; +import java.io.Serial; import java.io.Serializable; import java.util.Arrays; import java.util.List; @@ -31,6 +32,7 @@ */ @SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") abstract class FormatterStepEqualityOnStateSerialization implements FormatterStep, Serializable { + @Serial private static final long serialVersionUID = 1L; protected abstract State stateSupplier() throws Exception; @@ -75,8 +77,8 @@ public int hashCode() { @Override public void close() { - if (formatter instanceof FormatterFunc.Closeable) { - ((FormatterFunc.Closeable) formatter).close(); + if (formatter instanceof FormatterFunc.Closeable closeable) { + closeable.close(); formatter = null; } } diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterStepSerializationRoundtrip.java b/lib/src/main/java/com/diffplug/spotless/FormatterStepSerializationRoundtrip.java index f577760b74..77e9670380 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatterStepSerializationRoundtrip.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatterStepSerializationRoundtrip.java @@ -16,6 +16,7 @@ package com.diffplug.spotless; import java.io.IOException; +import java.io.Serial; import java.io.Serializable; import java.util.Objects; @@ -23,6 +24,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; final class FormatterStepSerializationRoundtrip extends FormatterStepEqualityOnStateSerialization { + @Serial private static final long serialVersionUID = 1L; private final String name; @SuppressFBWarnings(value = "SE_TRANSIENT_FIELD_NOT_RESTORED", justification = "HackClone") @@ -93,12 +95,12 @@ private void writeObject(java.io.ObjectOutputStream out) throws IOException { * It works in conjunction with ConfigurationCacheHackList to allow Spotless to work with all of Gradle's cache systems. */ static class HackClone implements Serializable { + @Serial private static final long serialVersionUID = 1L; @SuppressFBWarnings(value = "SE_TRANSIENT_FIELD_NOT_RESTORED", justification = "HackClone") transient FormatterStepSerializationRoundtrip original; boolean optimizeForEquality; - @Nullable - FormatterStepSerializationRoundtrip cleaned; + @Nullable FormatterStepSerializationRoundtrip cleaned; HackClone(@Nullable FormatterStepSerializationRoundtrip original, boolean optimizeForEquality) { this.original = original; diff --git a/lib/src/main/java/com/diffplug/spotless/JarState.java b/lib/src/main/java/com/diffplug/spotless/JarState.java index 76dee4f438..cee030075d 100644 --- a/lib/src/main/java/com/diffplug/spotless/JarState.java +++ b/lib/src/main/java/com/diffplug/spotless/JarState.java @@ -18,6 +18,7 @@ import java.io.File; import java.io.IOException; import java.io.ObjectStreamException; +import java.io.Serial; import java.io.Serializable; import java.net.URI; import java.net.URL; @@ -46,8 +47,7 @@ public final class JarState implements Serializable { private static final Logger logger = LoggerFactory.getLogger(JarState.class); // Let the classloader be overridden for tools using different approaches to classloading - @Nullable - private static ClassLoader forcedClassLoader = null; + @Nullable private static ClassLoader forcedClassLoader = null; /** Overrides the classloader used by all JarStates. */ public static void setForcedClassLoader(@Nullable ClassLoader forcedClassLoader) { @@ -59,6 +59,7 @@ public static void setForcedClassLoader(@Nullable ClassLoader forcedClassLoader) /** A lazily evaluated JarState, which becomes a set of files when serialized. */ public static class Promised implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final transient ThrowingEx.Supplier supplier; private FileSignature.Promised cached; @@ -100,6 +101,7 @@ public static Promised promise(ThrowingEx.Supplier supplier) { return new Promised(supplier); } + @Serial private static final long serialVersionUID = 1L; private final FileSignature fileSignature; diff --git a/lib/src/main/java/com/diffplug/spotless/Jvm.java b/lib/src/main/java/com/diffplug/spotless/Jvm.java index 3e8339644a..40b0b79c1a 100644 --- a/lib/src/main/java/com/diffplug/spotless/Jvm.java +++ b/lib/src/main/java/com/diffplug/spotless/Jvm.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,10 +90,10 @@ private Support(String formatterName, Comparator formatterVersionComp public Support add(int minimumJvmVersion, V maxFormatterVersion) { Objects.requireNonNull(maxFormatterVersion); if (null != jvm2fmtMaxVersion.put(minimumJvmVersion, maxFormatterVersion)) { - throw new IllegalArgumentException(String.format("Added duplicate entry for JVM %d+.", minimumJvmVersion)); + throw new IllegalArgumentException("Added duplicate entry for JVM %d+.".formatted(minimumJvmVersion)); } if (null != fmtMaxVersion2jvmVersion.put(maxFormatterVersion, minimumJvmVersion)) { - throw new IllegalArgumentException(String.format("Added duplicate entry for formatter version %s.", maxFormatterVersion)); + throw new IllegalArgumentException("Added duplicate entry for formatter version %s.".formatted(maxFormatterVersion)); } verifyVersionRangesDoNotIntersect(jvm2fmtMaxVersion, minimumJvmVersion, maxFormatterVersion); return this; @@ -102,7 +102,7 @@ public Support add(int minimumJvmVersion, V maxFormatterVersion) { public Support addMin(int minimumJvmVersion, V minFormatterVersion) { Objects.requireNonNull(minFormatterVersion); if (null != jvm2fmtMinVersion.put(minimumJvmVersion, minFormatterVersion)) { - throw new IllegalArgumentException(String.format("Added duplicate entry for JVM %d+.", minimumJvmVersion)); + throw new IllegalArgumentException("Added duplicate entry for JVM %d+.".formatted(minimumJvmVersion)); } verifyVersionRangesDoNotIntersect(jvm2fmtMinVersion, minimumJvmVersion, minFormatterVersion); return this; @@ -111,23 +111,21 @@ public Support addMin(int minimumJvmVersion, V minFormatterVersion) { private void verifyVersionRangesDoNotIntersect(NavigableMap jvm2fmtVersion, int minimumJvmVersion, V formatterVersion) { Map.Entry lower = jvm2fmtVersion.lowerEntry(minimumJvmVersion); if ((null != lower) && (fmtVersionComparator.compare(formatterVersion, lower.getValue()) <= 0)) { - throw new IllegalArgumentException(String.format("%d/%s should be lower than %d/%s", minimumJvmVersion, formatterVersion, lower.getKey(), lower.getValue())); + throw new IllegalArgumentException("%d/%s should be lower than %d/%s".formatted(minimumJvmVersion, formatterVersion, lower.getKey(), lower.getValue())); } Map.Entry higher = jvm2fmtVersion.higherEntry(minimumJvmVersion); if ((null != higher) && (fmtVersionComparator.compare(formatterVersion, higher.getValue()) >= 0)) { - throw new IllegalArgumentException(String.format("%d/%s should be higher than %d/%s", minimumJvmVersion, formatterVersion, higher.getKey(), higher.getValue())); + throw new IllegalArgumentException("%d/%s should be higher than %d/%s".formatted(minimumJvmVersion, formatterVersion, higher.getKey(), higher.getValue())); } } /** @return Highest formatter version recommended for this JVM (null, if JVM not supported) */ - @Nullable - public V getRecommendedFormatterVersion() { + @Nullable public V getRecommendedFormatterVersion() { Integer configuredJvmVersionOrNull = jvm2fmtMaxVersion.floorKey(Jvm.version()); return (null == configuredJvmVersionOrNull) ? null : jvm2fmtMaxVersion.get(configuredJvmVersionOrNull); } - @Nullable - public V getMinimumRequiredFormatterVersion() { + @Nullable public V getMinimumRequiredFormatterVersion() { Integer configuredJvmVersionOrNull = jvm2fmtMinVersion.floorKey(Jvm.version()); return (null == configuredJvmVersionOrNull) ? null : jvm2fmtMinVersion.get(configuredJvmVersionOrNull); } @@ -154,7 +152,7 @@ private String buildUnsupportedFormatterMessage(V fmtVersion) { // check if the formatter version is too low for the jvm version V minimumFormatterVersion = getMinimumRequiredFormatterVersion(); if ((null != minimumFormatterVersion) && (fmtVersionComparator.compare(fmtVersion, minimumFormatterVersion) < 0)) { - return String.format("You are running Spotless on JVM %d. This requires %s of at least %s (you are using %s).%n", Jvm.version(), fmtName, minimumFormatterVersion, fmtVersion); + return "You are running Spotless on JVM %d. This requires %s of at least %s (you are using %s).%n".formatted(Jvm.version(), fmtName, minimumFormatterVersion, fmtVersion); } // otherwise all is well return ""; @@ -162,16 +160,16 @@ private String buildUnsupportedFormatterMessage(V fmtVersion) { private String buildUpgradeJvmMessage(V fmtVersion) { StringBuilder builder = new StringBuilder(); - builder.append(String.format("You are running Spotless on JVM %d", Jvm.version())); + builder.append("You are running Spotless on JVM %d".formatted(Jvm.version())); V recommendedFmtVersionOrNull = getRecommendedFormatterVersion(); if (null != recommendedFmtVersionOrNull) { - builder.append(String.format(", which limits you to %s %s.%n", fmtName, recommendedFmtVersionOrNull)); + builder.append(", which limits you to %s %s.%n".formatted(fmtName, recommendedFmtVersionOrNull)); } else { Entry nextFmtVersionOrNull = fmtMaxVersion2jvmVersion.ceilingEntry(fmtVersion); if (null != nextFmtVersionOrNull) { - builder.append(String.format(". %s %s requires JVM %d+", fmtName, fmtVersion, nextFmtVersionOrNull.getValue())); + builder.append(". %s %s requires JVM %d+".formatted(fmtName, fmtVersion, nextFmtVersionOrNull.getValue())); } - builder.append(String.format(".%n")); + builder.append(".%n".formatted()); } return builder.toString(); } @@ -230,22 +228,22 @@ private String buildUpgradeFormatterMessage(V fmtVersion) { V minimumFormatterVersion = getMinimumRequiredFormatterVersion(); V recommendedFmtVersionOrNull = getRecommendedFormatterVersion(); if ((null != minimumFormatterVersion) && (fmtVersionComparator.compare(fmtVersion, minimumFormatterVersion) < 0)) { - builder.append(String.format("You are running Spotless on JVM %d. This requires %s of at least %s.%n", Jvm.version(), fmtName, minimumFormatterVersion)); - builder.append(String.format("You are using %s %s.%n", fmtName, fmtVersion)); + builder.append("You are running Spotless on JVM %d. This requires %s of at least %s.%n".formatted(Jvm.version(), fmtName, minimumFormatterVersion)); + builder.append("You are using %s %s.%n".formatted(fmtName, fmtVersion)); if (null != recommendedFmtVersionOrNull) { - builder.append(String.format("%s %s is the recommended version, which may have fixed this problem.%n", fmtName, recommendedFmtVersionOrNull)); + builder.append("%s %s is the recommended version, which may have fixed this problem.%n".formatted(fmtName, recommendedFmtVersionOrNull)); } // check if the formatter is outdated on this jvm } else if (null != recommendedFmtVersionOrNull && (fmtVersionComparator.compare(fmtVersion, recommendedFmtVersionOrNull) < 0)) { - builder.append(String.format("%s %s is currently being used, but outdated.%n", fmtName, fmtVersion)); - builder.append(String.format("%s %s is the recommended version, which may have fixed this problem.%n", fmtName, recommendedFmtVersionOrNull)); - builder.append(String.format("%s %s requires JVM %d+.", fmtName, recommendedFmtVersionOrNull, getRequiredJvmVersion(recommendedFmtVersionOrNull))); + builder.append("%s %s is currently being used, but outdated.%n".formatted(fmtName, fmtVersion)); + builder.append("%s %s is the recommended version, which may have fixed this problem.%n".formatted(fmtName, recommendedFmtVersionOrNull)); + builder.append("%s %s requires JVM %d+.".formatted(fmtName, recommendedFmtVersionOrNull, getRequiredJvmVersion(recommendedFmtVersionOrNull))); } else { V higherFormatterVersionOrNull = fmtMaxVersion2jvmVersion.higherKey(fmtVersion); if (null != higherFormatterVersionOrNull) { builder.append(buildUpgradeJvmMessage(fmtVersion)); Integer higherJvmVersion = fmtMaxVersion2jvmVersion.get(higherFormatterVersionOrNull); - builder.append(String.format("If you upgrade your JVM to %d+, then you can use %s %s, which may have fixed this problem.", higherJvmVersion, fmtName, higherFormatterVersionOrNull)); + builder.append("If you upgrade your JVM to %d+, then you can use %s %s, which may have fixed this problem.".formatted(higherJvmVersion, fmtName, higherFormatterVersionOrNull)); } } return builder.toString(); @@ -253,9 +251,9 @@ private String buildUpgradeFormatterMessage(V fmtVersion) { @Override public String toString() { - return String.format("%s alternatives:%n", fmtName) + + return "%s alternatives:%n".formatted(fmtName) + jvm2fmtMaxVersion.entrySet().stream().map( - e -> String.format("- Version %s requires JVM %d+", e.getValue(), e.getKey())).collect(Collectors.joining(System.lineSeparator())); + e -> "- Version %s requires JVM %d+".formatted(e.getValue(), e.getKey())).collect(Collectors.joining(System.lineSeparator())); } @SuppressFBWarnings("SE_COMPARATOR_SHOULD_BE_SERIALIZABLE") @@ -288,7 +286,7 @@ private static int[] convert(V versionObject) { } return Arrays.asList(versionString.split("\\.")).stream().mapToInt(Integer::parseInt).toArray(); } catch (Exception e) { - throw new IllegalArgumentException(String.format("Not a semantic version: %s", versionObject), e); + throw new IllegalArgumentException("Not a semantic version: %s".formatted(versionObject), e); } } }; diff --git a/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java b/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java index f81570cedf..443deb7ac3 100644 --- a/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java +++ b/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java @@ -21,6 +21,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamException; +import java.io.Serial; import java.io.Serializable; import java.util.Arrays; import java.util.Objects; @@ -33,11 +34,11 @@ * equals() and hashCode(), so you don't have to. */ public abstract class LazyForwardingEquality implements Serializable, NoLambda { + @Serial private static final long serialVersionUID = 1L; /** Lazily initialized - null indicates that the state has not yet been set. */ - @Nullable - private transient volatile T state; + @Nullable private transient volatile T state; /** * This function is guaranteed to be called at most once. @@ -124,10 +125,10 @@ static Object fromBytes(byte[] bytes) { /** Ensures that the lazy state has been evaluated. */ public static void unlazy(Object in) { - if (in instanceof LazyForwardingEquality) { - ((LazyForwardingEquality) in).state(); - } else if (in instanceof DelegateFormatterStep) { - unlazy(((DelegateFormatterStep) in).delegateStep); + if (in instanceof LazyForwardingEquality equality) { + equality.state(); + } else if (in instanceof DelegateFormatterStep step) { + unlazy(step.delegateStep); } else if (in instanceof Iterable) { Iterable cast = (Iterable) in; for (Object c : cast) { diff --git a/lib/src/main/java/com/diffplug/spotless/LineEnding.java b/lib/src/main/java/com/diffplug/spotless/LineEnding.java index 5b44b81889..3fbcb5afa0 100644 --- a/lib/src/main/java/com/diffplug/spotless/LineEnding.java +++ b/lib/src/main/java/com/diffplug/spotless/LineEnding.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import java.io.FileReader; import java.io.IOException; import java.io.Reader; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; @@ -93,7 +94,7 @@ public Policy createPolicy() { } static class ConstantLineEndingPolicy extends NoLambda.EqualityBasedOnSerialization implements Policy { - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; final String lineEnding; @@ -108,7 +109,7 @@ public String getEndingFor(File file) { } static class PreserveLineEndingPolicy extends NoLambda.EqualityBasedOnSerialization implements Policy { - private static final long serialVersionUID = 2L; + @Serial private static final long serialVersionUID = 2L; @Override public String getEndingFor(File file) { diff --git a/lib/src/main/java/com/diffplug/spotless/Lint.java b/lib/src/main/java/com/diffplug/spotless/Lint.java index b01a072905..fb91232d8c 100644 --- a/lib/src/main/java/com/diffplug/spotless/Lint.java +++ b/lib/src/main/java/com/diffplug/spotless/Lint.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless; +import java.io.Serial; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; @@ -41,6 +42,7 @@ public static Lint atLineRange(int lineStart, int lineEnd, String shortCode, Str return new Lint(lineStart, lineEnd, shortCode, detail); } + @Serial private static final long serialVersionUID = 1L; private int lineStart, lineEnd; // 1-indexed, inclusive diff --git a/lib/src/main/java/com/diffplug/spotless/LintState.java b/lib/src/main/java/com/diffplug/spotless/LintState.java index 3068872256..bc4cf9e64b 100644 --- a/lib/src/main/java/com/diffplug/spotless/LintState.java +++ b/lib/src/main/java/com/diffplug/spotless/LintState.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -181,8 +181,8 @@ public static LintState of(Formatter formatter, File file, byte[] rawBytes) { } } List lintsForStep; - if (exceptionForLint instanceof Lint.Has) { - lintsForStep = ((Lint.Has) exceptionForLint).getLints(); + if (exceptionForLint instanceof Lint.Has has) { + lintsForStep = has.getLints(); } else if (exceptionForLint != null && exceptionForLint != formatStepCausedNoChange()) { lintsForStep = List.of(Lint.createFromThrowable(step, exceptionForLint)); } else { diff --git a/lib/src/main/java/com/diffplug/spotless/LintSuppression.java b/lib/src/main/java/com/diffplug/spotless/LintSuppression.java index bf4d410a04..b36cb2a0e7 100644 --- a/lib/src/main/java/com/diffplug/spotless/LintSuppression.java +++ b/lib/src/main/java/com/diffplug/spotless/LintSuppression.java @@ -16,11 +16,13 @@ package com.diffplug.spotless; import java.io.File; +import java.io.Serial; import java.util.Objects; import javax.annotation.Nullable; public class LintSuppression implements java.io.Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String ALL = "*"; diff --git a/lib/src/main/java/com/diffplug/spotless/MoreIterables.java b/lib/src/main/java/com/diffplug/spotless/MoreIterables.java index c3b0e5f286..22832aa678 100644 --- a/lib/src/main/java/com/diffplug/spotless/MoreIterables.java +++ b/lib/src/main/java/com/diffplug/spotless/MoreIterables.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,8 @@ private MoreIterables() {} /** Returns a shallow copy of input elements, throwing on null elements. */ static List toNullHostileList(Iterable input) { requireElementsNonNull(input); - List shallowCopy = (input instanceof Collection) - ? new ArrayList<>(((Collection) input).size()) + List shallowCopy = (input instanceof Collection c) + ? new ArrayList<>(c.size()) : new ArrayList<>(); input.forEach(shallowCopy::add); return shallowCopy; diff --git a/lib/src/main/java/com/diffplug/spotless/NoLambda.java b/lib/src/main/java/com/diffplug/spotless/NoLambda.java index d2ca6c1401..f292d1549e 100644 --- a/lib/src/main/java/com/diffplug/spotless/NoLambda.java +++ b/lib/src/main/java/com/diffplug/spotless/NoLambda.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless; +import java.io.Serial; import java.io.Serializable; import java.util.Arrays; @@ -44,6 +45,7 @@ public interface NoLambda extends Serializable { /** An implementation of NoLambda in which equality is based on the serialized representation of itself. */ public static abstract class EqualityBasedOnSerialization implements NoLambda { + @Serial private static final long serialVersionUID = 1733798699224768949L; @Override diff --git a/lib/src/main/java/com/diffplug/spotless/SerializedFunction.java b/lib/src/main/java/com/diffplug/spotless/SerializedFunction.java index 7cadb120d6..77a1a8f529 100644 --- a/lib/src/main/java/com/diffplug/spotless/SerializedFunction.java +++ b/lib/src/main/java/com/diffplug/spotless/SerializedFunction.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless; +import java.io.Serial; import java.io.Serializable; @FunctionalInterface @@ -28,6 +29,7 @@ static SerializedFunction alwaysReturns(R value) { } class AlwaysReturns implements SerializedFunction { + @Serial private static final long serialVersionUID = 1L; private final R value; diff --git a/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java b/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java index 9828b7d748..82cdd5d3c2 100644 --- a/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java +++ b/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java @@ -50,8 +50,8 @@ static final class SerializedKey { @Override public final boolean equals(Object other) { - return other instanceof SerializedKey - && Arrays.equals(serialized, ((SerializedKey) other).serialized); + return other instanceof SerializedKey sk + && Arrays.equals(serialized, sk.serialized); } @Override diff --git a/lib/src/main/java/com/diffplug/spotless/ThrowingEx.java b/lib/src/main/java/com/diffplug/spotless/ThrowingEx.java index 7e017e0989..ff7e4d9c08 100644 --- a/lib/src/main/java/com/diffplug/spotless/ThrowingEx.java +++ b/lib/src/main/java/com/diffplug/spotless/ThrowingEx.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,8 +89,8 @@ public static java.util.function.Function wrap(ThrowingEx.Function< * {@link WrappedAsRuntimeException} and returned. */ public static RuntimeException asRuntime(Exception e) { - if (e instanceof RuntimeException) { - return (RuntimeException) e; + if (e instanceof RuntimeException exception) { + return exception; } else { return new WrappedAsRuntimeException(e); } @@ -128,10 +128,10 @@ public static RuntimeException unwrapCause(Throwable e) { * } */ static RuntimeException asRuntimeRethrowError(Throwable e) { - if (e instanceof Error) { - throw (Error) e; - } else if (e instanceof RuntimeException) { - return (RuntimeException) e; + if (e instanceof Error error) { + throw error; + } else if (e instanceof RuntimeException exception) { + return exception; } else { return new WrappedAsRuntimeException(e); } diff --git a/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4FormatterStep.java b/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4FormatterStep.java index e62ac29332..1852cf35d9 100644 --- a/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4FormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4FormatterStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.antlr4; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -26,6 +27,7 @@ import com.diffplug.spotless.ThrowingEx; public class Antlr4FormatterStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATE = "com.khubla.antlr4formatter:antlr4-formatter:"; private static final String DEFAULT_VERSION = "1.2.1"; @@ -57,6 +59,7 @@ private State equalityState() { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final JarState jarState; diff --git a/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java b/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java index 5512dd7c4c..3aac619d02 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java @@ -50,7 +50,7 @@ final class BiomeExecutableDownloader { private static final String CHECKSUM_ALGORITHM = "SHA-256"; /** - * The pattern for {@link String#format(String, Object...) String.format()} for + * The pattern for {@link String#formatted(Object...) String.format()} for * the platform part of the Biome executable download URL. First parameter is the * OS, second parameter the architecture, the third the file extension. */ @@ -277,8 +277,8 @@ private String getDownloadUrl(String version, Platform platform) throws IOExcept var osCodeName = getOsCodeName(platform.getOs()); var architectureCodeName = getArchitectureCodeName(platform.getArchitecture()); var extension = getDownloadUrlExtension(platform.getOs()); - var platformString = String.format(PLATFORM_PATTERN, osCodeName, architectureCodeName, extension); - return String.format(BiomeSettings.getUrlPattern(version), version, platformString); + var platformString = PLATFORM_PATTERN.formatted(osCodeName, architectureCodeName, extension); + return BiomeSettings.getUrlPattern(version).formatted(version, platformString); } /** @@ -313,7 +313,7 @@ private String getDownloadUrlExtension(OS os) throws IOException { private Path getExecutablePath(String version, Platform platform) { var os = platform.getOs().name().toLowerCase(Locale.ROOT); var arch = platform.getArchitecture().name().toLowerCase(Locale.ROOT); - var fileName = String.format(BiomeSettings.getDownloadFilePattern(), os, arch, version); + var fileName = BiomeSettings.getDownloadFilePattern().formatted(os, arch, version); return downloadDir.resolve(fileName); } diff --git a/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java b/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java index 14157a6295..82194c2a13 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java @@ -48,7 +48,7 @@ public static String defaultVersion() { } /** - * @return The pattern for {@link String#format(String, Object...) + * @return The pattern for {@link String#formatted(Object...) * String.format()} for the file name of a Biome executable for a * certain version and architecture. The first parameter is the platform, * the second is the OS, the third is the architecture. @@ -59,7 +59,7 @@ public static String getDownloadFilePattern() { /** * @param version The biome version for which to get the URL pattern, e.g. 1.2.0 or 2.0.6. - * @return The pattern for {@link String#format(String, Object...) + * @return The pattern for {@link String#formatted(Object...) * String.format()} for the URL where the executables can be downloaded. * The first parameter is the version, the second parameter is the OS / * platform. diff --git a/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java b/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java index 2ebb9d75c5..9b580ead51 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java @@ -22,7 +22,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; import java.util.ArrayList; import java.util.Collections; @@ -161,7 +160,7 @@ private static String defaultVersion() { * @param filePath Path to the file to make executable. */ private static void makeExecutable(String filePath) { - var exePath = Paths.get(filePath); + var exePath = Path.of(filePath); attemptToAddPosixPermission(exePath, PosixFilePermission.GROUP_EXECUTE); attemptToAddPosixPermission(exePath, PosixFilePermission.OTHERS_EXECUTE); attemptToAddPosixPermission(exePath, PosixFilePermission.OWNER_EXECUTE); @@ -199,7 +198,7 @@ private static void validateBiomeConfigPath(String configPath, String version) { return; } var atLeastV2 = BiomeSettings.versionHigherThanOrEqualTo(version, 2, 0, 0); - var path = Paths.get(configPath); + var path = Path.of(configPath); var configFile = Files.isRegularFile(path) && atLeastV2 ? path : path.resolve(BiomeSettings.configName()); if (!Files.exists(path)) { throw new IllegalArgumentException("Biome config directory does not exist: " + path); @@ -323,13 +322,13 @@ private State createState() throws IOException, InterruptedException { private String resolveExe() throws IOException, InterruptedException { new ForeignExe(); if (pathToExe != null) { - if (Paths.get(pathToExe).getNameCount() == 1) { + if (Path.of(pathToExe).getNameCount() == 1) { return resolveNameAgainstPath(pathToExe); } else { return pathToExe; } } else { - var downloader = new BiomeExecutableDownloader(Paths.get(downloadDir)); + var downloader = new BiomeExecutableDownloader(Path.of(downloadDir)); var downloaded = downloader.ensureDownloaded(version).toString(); makeExecutable(downloaded); return downloaded; diff --git a/lib/src/main/java/com/diffplug/spotless/biome/Platform.java b/lib/src/main/java/com/diffplug/spotless/biome/Platform.java index 590e303d98..82d86e9a73 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/Platform.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/Platform.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,6 +86,6 @@ public boolean isWindows() { @Override public String toString() { - return String.format("Platform[os=%s,architecture=%s]", os, architecture); + return "Platform[os=%s,architecture=%s]".formatted(os, architecture); } } diff --git a/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java b/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java index 64a43bf439..39c1001725 100644 --- a/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2024 DiffPlug + * Copyright 2020-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,14 +68,14 @@ public FormatterStep create() { } private RoundtripState createRoundtrip() throws IOException, InterruptedException { - String howToInstall = "" + - "You can download clang-format from https://releases.llvm.org and " + - "then point Spotless to it with {@code pathToExe('/path/to/clang-format')} " + - "or you can use your platform's package manager:" + - "\n win: choco install llvm --version {version} (try dropping version if it fails)" + - "\n mac: brew install clang-format (TODO: how to specify version?)" + - "\n linux: apt install clang-format (try clang-format-{version} with dropped minor versions)" + - "\n github issue to handle this better: https://github.com/diffplug/spotless/issues/673"; + String howToInstall = """ + You can download clang-format from https://releases.llvm.org and \ + then point Spotless to it with {@code pathToExe('/path/to/clang-format')} \ + or you can use your platform's package manager: + win: choco install llvm --version {version} (try dropping version if it fails) + mac: brew install clang-format (TODO: how to specify version?) + linux: apt install clang-format (try clang-format-{version} with dropped minor versions) + github issue to handle this better: https://github.com/diffplug/spotless/issues/673"""; final ForeignExe exe = ForeignExe.nameAndVersion("clang-format", version) .pathToExe(pathToExe) .fixCantFind(howToInstall) diff --git a/lib/src/main/java/com/diffplug/spotless/generic/IdeaStep.java b/lib/src/main/java/com/diffplug/spotless/generic/IdeaStep.java index 209a0d7560..9b90964a3f 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/IdeaStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/IdeaStep.java @@ -124,8 +124,7 @@ public FormatterStep build() { @Override public String toString() { - return String.format( - "IdeaStepBuilder[useDefaults=%s, binaryPath=%s, codeStyleSettingsPath=%s, ideaProperties=%s, buildDir=%s]", + return "IdeaStepBuilder[useDefaults=%s, binaryPath=%s, codeStyleSettingsPath=%s, ideaProperties=%s, buildDir=%s]".formatted( this.useDefaults, this.binaryPath, this.codeStyleSettingsPath, @@ -175,7 +174,7 @@ private static String resolveFullBinaryPathAndCheckVersion(String binaryPath) { @CheckForNull private static String pathToExe(String binaryPath) { - String testEnvBinaryPath = TestEnvVars.read().get(String.format("%s.%s", IdeaStep.class.getName(), "binaryPath")); + String testEnvBinaryPath = TestEnvVars.read().get("%s.%s".formatted(IdeaStep.class.getName(), "binaryPath")); if (testEnvBinaryPath != null) { return testEnvBinaryPath; } @@ -247,7 +246,7 @@ private File createIdeaPropertiesFile() { Path parent = ideaProps.getParent(); if (parent == null) { - throw new IllegalStateException(String.format("Parent directory for IDEA properties file %s cannot be null", ideaProps)); + throw new IllegalStateException("Parent directory for IDEA properties file %s cannot be null".formatted(ideaProps)); } ThrowingEx.run(() -> Files.createDirectories(parent)); diff --git a/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java b/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java index 91155b1a79..1522adf947 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.generic; +import java.io.Serial; import java.io.Serializable; import com.diffplug.spotless.FormatterFunc; @@ -23,6 +24,7 @@ /** Simple step which checks for consistent indentation characters. */ public final class IndentStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; final Type type; diff --git a/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java b/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java index 572bf13b95..fd634f50cf 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.generic; +import java.io.Serial; import java.io.Serializable; import java.util.Objects; import java.util.stream.Collectors; @@ -29,9 +30,9 @@ import com.diffplug.spotless.Provisioner; public final class Jsr223Step implements Serializable { + @Serial private static final long serialVersionUID = 1L; - @Nullable - private final JarState.Promised jarState; + @Nullable private final JarState.Promised jarState; private final String engine; private final String script; @@ -56,10 +57,10 @@ private State equalityState() { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; - @Nullable - private final JarState jarState; + @Nullable private final JarState jarState; private final String engine; private final String script; diff --git a/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsConfig.java b/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsConfig.java index d7962c6543..2b499f1f18 100644 --- a/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,11 @@ */ package com.diffplug.spotless.gherkin; +import java.io.Serial; import java.io.Serializable; public class GherkinUtilsConfig implements Serializable { + @Serial private static final long serialVersionUID = 1L; public static int defaultIndentSpaces() { diff --git a/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsStep.java b/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsStep.java index 4f606332d0..de791303c0 100644 --- a/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsStep.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.gherkin; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -26,6 +27,7 @@ import com.diffplug.spotless.Provisioner; public class GherkinUtilsStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATE = "io.cucumber:gherkin-utils:"; private static final String DEFAULT_VERSION = "9.2.0"; @@ -57,6 +59,7 @@ private State equalityState() { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final GherkinUtilsConfig gherkinSimpleConfig; diff --git a/lib/src/main/java/com/diffplug/spotless/groovy/RemoveSemicolonsStep.java b/lib/src/main/java/com/diffplug/spotless/groovy/RemoveSemicolonsStep.java index 6dc3185ef6..c701be63ee 100644 --- a/lib/src/main/java/com/diffplug/spotless/groovy/RemoveSemicolonsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/groovy/RemoveSemicolonsStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package com.diffplug.spotless.groovy; import java.io.BufferedReader; +import java.io.Serial; import java.io.Serializable; import java.io.StringReader; @@ -28,6 +29,7 @@ * @author Jose Luis Badano */ public final class RemoveSemicolonsStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String NAME = "Remove unnecessary semicolons"; @@ -42,6 +44,7 @@ public static FormatterStep create() { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; FormatterFunc toFormatter() { diff --git a/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java b/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java index 7790c8b06a..ef10b7ec2f 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java @@ -16,6 +16,7 @@ package com.diffplug.spotless.java; import java.io.File; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Method; @@ -37,6 +38,7 @@ */ // https://github.com/diffplug/spotless/blob/main/CONTRIBUTING.md#how-to-add-a-new-formatterstep public final class CleanthatJavaStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String NAME = "cleanthat"; private static final String MAVEN_COORDINATE = "io.github.solven-eu.cleanthat:java"; @@ -146,6 +148,7 @@ private State equalityState() { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final JarState jarState; diff --git a/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java b/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java index 998c147ef5..3de76313f7 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2022-2024 DiffPlug + * Copyright 2022-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.java; +import java.io.Serial; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; @@ -38,6 +39,7 @@ * Note: A type annotation is an annotation that is meta-annotated with {@code @Target({ElementType.TYPE_USE})}. */ public final class FormatAnnotationsStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; /** @@ -426,6 +428,7 @@ private FormatAnnotationsStep() {} // TODO: Read from a local .type-annotations file. private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final Set typeAnnotations = new HashSet<>(defaultTypeAnnotations); diff --git a/lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java b/lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java index c4f763685f..4ac3357426 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.java; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.util.Objects; @@ -27,6 +28,7 @@ /** Wraps up google-java-format as a FormatterStep. */ public class GoogleJavaFormatStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String DEFAULT_STYLE = "GOOGLE"; private static final boolean DEFAULT_REFLOW_LONG_STRINGS = false; @@ -153,6 +155,7 @@ private State equalityState() { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final JarState jarState; diff --git a/lib/src/main/java/com/diffplug/spotless/java/ImportOrderStep.java b/lib/src/main/java/com/diffplug/spotless/java/ImportOrderStep.java index 7f2aa7ec4d..62596ef42c 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/ImportOrderStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/ImportOrderStep.java @@ -19,6 +19,7 @@ import java.io.File; import java.io.IOException; +import java.io.Serial; import java.io.Serializable; import java.io.UncheckedIOException; import java.nio.file.Files; @@ -41,6 +42,7 @@ import com.diffplug.spotless.SerializedFunction; public final class ImportOrderStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final boolean WILDCARDS_LAST_DEFAULT = false; private static final boolean SEMANTIC_SORT_DEFAULT = false; @@ -113,6 +115,7 @@ private static Map.Entry splitIntoIndexAndName(String line) { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final List importOrder; diff --git a/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java b/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java index 4393de95a3..a8df9b0a1d 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java +++ b/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,15 @@ package com.diffplug.spotless.java; import java.io.Serializable; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -212,7 +220,7 @@ private List getResult(List sortedImported, String lineFormat) { if (s.equals(ImportSorter.N)) { strings.add(s); } else { - strings.add(String.format(lineFormat, s) + ImportSorter.N); + strings.add(lineFormat.formatted(s) + ImportSorter.N); } } return strings; diff --git a/lib/src/main/java/com/diffplug/spotless/java/ModuleHelper.java b/lib/src/main/java/com/diffplug/spotless/java/ModuleHelper.java index e05a6a8b7f..4466f96eaf 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/ModuleHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/java/ModuleHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ public static synchronized void doOpenInternalPackagesIfRequired() { message.append("WARNING: Some required internal classes are unavailable. Please consider adding the following JVM arguments\n"); message.append("WARNING: "); for (String name : failedToOpen) { - message.append(String.format("--add-opens jdk.compiler/%s=ALL-UNNAMED", name)); + message.append("--add-opens jdk.compiler/%s=ALL-UNNAMED".formatted(name)); } LOGGER.warn("{}", message); } @@ -127,8 +127,7 @@ private static void openPackages(Collection packagesToOpen) throws Throw } } - @Nullable - @SuppressFBWarnings("REC_CATCH_EXCEPTION") // workaround JDK11 + @Nullable @SuppressFBWarnings("REC_CATCH_EXCEPTION") // workaround JDK11 private static Collection allModules() { // calling ModuleLayer.boot().modules() by reflection try { diff --git a/lib/src/main/java/com/diffplug/spotless/java/PalantirJavaFormatStep.java b/lib/src/main/java/com/diffplug/spotless/java/PalantirJavaFormatStep.java index a3adb3b941..354f08e084 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/PalantirJavaFormatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/PalantirJavaFormatStep.java @@ -15,15 +15,21 @@ */ package com.diffplug.spotless.java; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.util.Objects; -import com.diffplug.spotless.*; +import com.diffplug.spotless.FormatterFunc; +import com.diffplug.spotless.FormatterStep; +import com.diffplug.spotless.JarState; +import com.diffplug.spotless.Jvm; +import com.diffplug.spotless.Provisioner; /** Wraps up palantir-java-format fork of * google-java-format as a FormatterStep. */ public class PalantirJavaFormatStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final boolean DEFAULT_FORMAT_JAVADOC = false; private static final String DEFAULT_STYLE = "PALANTIR"; @@ -102,6 +108,7 @@ private State equalityState() { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final JarState jarState; diff --git a/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java b/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java index 71b6dc4281..187ee8b6a4 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.java; +import java.io.Serial; import java.io.Serializable; import java.util.List; import java.util.Objects; @@ -24,6 +25,7 @@ /** Uses google-java-format or cleanthat.UnnecessaryImport, but only to remove unused imports. */ public class RemoveUnusedImportsStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; static final String NAME = "removeUnusedImports"; diff --git a/lib/src/main/java/com/diffplug/spotless/json/JacksonConfig.java b/lib/src/main/java/com/diffplug/spotless/json/JacksonConfig.java index 6a35a1e693..2363c15069 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/JacksonConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/json/JacksonConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.json; +import java.io.Serial; import java.io.Serializable; import java.util.Collections; import java.util.LinkedHashMap; @@ -25,6 +26,7 @@ * A DTO holding the basic for Jackson-based formatters */ public class JacksonConfig implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final Map DEFAULT_FEATURE_TOGGLES; diff --git a/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonConfig.java b/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonConfig.java index efff594663..41a5501fc2 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.json; +import java.io.Serial; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; @@ -23,6 +24,7 @@ * Specialization of {@link JacksonConfig} for JSON documents */ public class JacksonJsonConfig extends JacksonConfig { + @Serial private static final long serialVersionUID = 1L; protected Map jsonFeatureToToggle = new LinkedHashMap<>(); diff --git a/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonStep.java b/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonStep.java index bd42e8d35e..c56921458c 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonStep.java +++ b/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonStep.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.json; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -30,6 +31,7 @@ */ // https://stackoverflow.com/questions/14515994/convert-json-string-to-pretty-print-json-output-using-jackson public class JacksonJsonStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATE = "com.fasterxml.jackson.core:jackson-databind:"; private static final String DEFAULT_VERSION = "2.20.0"; @@ -66,6 +68,7 @@ private State equalityState() { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final JacksonConfig jacksonConfig; diff --git a/lib/src/main/java/com/diffplug/spotless/json/JsonPatchStep.java b/lib/src/main/java/com/diffplug/spotless/json/JsonPatchStep.java index 2589e986a2..0b5f4c9d73 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/JsonPatchStep.java +++ b/lib/src/main/java/com/diffplug/spotless/json/JsonPatchStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.json; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -30,16 +31,15 @@ import com.diffplug.spotless.Provisioner; public class JsonPatchStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATE = "com.flipkart.zjsonpatch:zjsonpatch"; private static final String DEFAULT_VERSION = "0.4.16"; public static final String NAME = "apply-json-patch"; private final JarState.Promised jarState; - @Nullable - private final List> patch; - @Nullable - private final String patchString; + @Nullable private final List> patch; + @Nullable private final String patchString; private JsonPatchStep(JarState.Promised jarState, @Nullable String patchString, @@ -82,13 +82,12 @@ private State equalityState() { } static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final JarState jarState; - @Nullable - private final List> patch; - @Nullable - private final String patchString; + @Nullable private final List> patch; + @Nullable private final String patchString; State(JarState jarState, @Nullable String patchString, diff --git a/lib/src/main/java/com/diffplug/spotless/json/JsonSimpleStep.java b/lib/src/main/java/com/diffplug/spotless/json/JsonSimpleStep.java index c42bf3cf9c..3fbe8ae7b9 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/JsonSimpleStep.java +++ b/lib/src/main/java/com/diffplug/spotless/json/JsonSimpleStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.json; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -30,6 +31,7 @@ * Simple JSON formatter which reformats the file according to the org.json library's default pretty-printing, but has no ability to customise more than the indentation size. */ public final class JsonSimpleStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATE = "org.json:json:"; private static final String DEFAULT_VERSION = "20210307"; @@ -56,6 +58,7 @@ private State equalityState() { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final int indentSpaces; @@ -97,7 +100,7 @@ FormatterFunc toFormatter() { return format(arrayConstructor, arrayToString, s); } - throw new IllegalArgumentException(String.format("Unable to determine JSON type, expected a '{' or '[' but found '%s'", first)); + throw new IllegalArgumentException("Unable to determine JSON type, expected a '{' or '[' but found '%s'".formatted(first)); }; } diff --git a/lib/src/main/java/com/diffplug/spotless/json/gson/GsonConfig.java b/lib/src/main/java/com/diffplug/spotless/json/gson/GsonConfig.java index a11c1ee296..05d602df83 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/gson/GsonConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/json/gson/GsonConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,11 @@ */ package com.diffplug.spotless.json.gson; +import java.io.Serial; import java.io.Serializable; public class GsonConfig implements Serializable { + @Serial private static final long serialVersionUID = 6039715618937332633L; private boolean sortByKeys; diff --git a/lib/src/main/java/com/diffplug/spotless/json/gson/GsonStep.java b/lib/src/main/java/com/diffplug/spotless/json/gson/GsonStep.java index 0ca60c7e31..de11c4d9d9 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/gson/GsonStep.java +++ b/lib/src/main/java/com/diffplug/spotless/json/gson/GsonStep.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.json.gson; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -26,6 +27,7 @@ import com.diffplug.spotless.Provisioner; public class GsonStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATES = "com.google.code.gson:gson"; private static final String INCOMPATIBLE_ERROR_MESSAGE = "There was a problem interacting with Gson; maybe you set an incompatible version?"; @@ -53,6 +55,7 @@ private State equalityState() { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = -3240568265160440420L; private final JarState jarState; diff --git a/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java b/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java index daf101d9ce..c1aa695040 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,22 @@ package com.diffplug.spotless.kotlin; import java.io.File; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; -import java.util.*; +import java.util.Objects; import javax.annotation.Nullable; -import com.diffplug.spotless.*; +import com.diffplug.spotless.FileSignature; +import com.diffplug.spotless.FormatterFunc; +import com.diffplug.spotless.FormatterStep; +import com.diffplug.spotless.JarState; +import com.diffplug.spotless.Provisioner; /** Wraps up diktat as a FormatterStep. */ public class DiktatStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final JarState.Promised jarState; private final String versionDiktat; @@ -86,6 +92,7 @@ private State equalityState() throws Exception { } static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; final JarState jar; diff --git a/lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java b/lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java index 90f73d062c..7cdd102b10 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.kotlin; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.util.Collections; @@ -35,6 +36,7 @@ /** Wraps up ktlint as a FormatterStep. */ public class KtLintStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String DEFAULT_VERSION = "1.7.1"; private static final String NAME = "ktlint"; @@ -89,6 +91,7 @@ private State equalityState() { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; /** The jar that contains the formatter. */ private final JarState jarState; diff --git a/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java b/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java index b30044ff2c..865a3e37c4 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java @@ -20,6 +20,7 @@ import static com.diffplug.spotless.kotlin.KtfmtStep.Style.META; import static com.diffplug.spotless.kotlin.KtfmtStep.TrailingCommaManagementStrategy.ONLY_ADD; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -39,6 +40,7 @@ * Wraps up ktfmt as a FormatterStep. */ public class KtfmtStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String DEFAULT_VERSION = "0.58"; private static final String NAME = "ktfmt"; @@ -142,6 +144,7 @@ public enum TrailingCommaManagementStrategy { public static class KtfmtFormattingOptions implements Serializable { + @Serial private static final long serialVersionUID = 1L; @Nullable private Integer maxWidth = null; @@ -225,6 +228,7 @@ private State equalityState() { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final String version; @Nullable private final Style style; @@ -310,10 +314,10 @@ private void validateStyle() { } if (BadSemver.version(version) < BadSemver.version(style.since)) { - throw new IllegalStateException(String.format("The style %s is available from version %s (current version: %s)", style.name(), style.since, version)); + throw new IllegalStateException("The style %s is available from version %s (current version: %s)".formatted(style.name(), style.since, version)); } if (style.until != null && BadSemver.version(version) > BadSemver.version(style.until)) { - throw new IllegalStateException(String.format("The style %s is no longer available from version %s (current version: %s)", style.name(), style.until, version)); + throw new IllegalStateException("The style %s is no longer available from version %s (current version: %s)".formatted(style.name(), style.until, version)); } } diff --git a/lib/src/main/java/com/diffplug/spotless/markdown/FlexmarkStep.java b/lib/src/main/java/com/diffplug/spotless/markdown/FlexmarkStep.java index 359e5b5de0..bce55abb69 100644 --- a/lib/src/main/java/com/diffplug/spotless/markdown/FlexmarkStep.java +++ b/lib/src/main/java/com/diffplug/spotless/markdown/FlexmarkStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.markdown; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.util.Objects; @@ -26,6 +27,7 @@ /** A step for flexmark-java. */ public class FlexmarkStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String DEFAULT_VERSION = "0.64.8"; private static final String MAVEN_COORDINATE = "com.vladsch.flexmark:flexmark-all:"; @@ -61,6 +63,7 @@ private State equalityState() { } private static class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final JarState jarState; diff --git a/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java b/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java index 4786474657..6149a736e1 100644 --- a/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java +++ b/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ import static com.diffplug.spotless.markdown.LibMarkdownPreconditions.requireKeysAndValuesNonNull; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; @@ -38,6 +39,7 @@ /** A step for FreshMark. */ public class FreshMarkStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String DEFAULT_VERSION = "1.3.1"; @@ -91,6 +93,7 @@ private State equalityState() throws Exception { } private static class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final JarState jarState; diff --git a/lib/src/main/java/com/diffplug/spotless/npm/BlacklistedOptionException.java b/lib/src/main/java/com/diffplug/spotless/npm/BlacklistedOptionException.java index 3704f487dc..a2a12c4f1f 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/BlacklistedOptionException.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/BlacklistedOptionException.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,10 @@ */ package com.diffplug.spotless.npm; +import java.io.Serial; + class BlacklistedOptionException extends RuntimeException { + @Serial private static final long serialVersionUID = -5876348893394153811L; public BlacklistedOptionException(String blacklistedOption) { diff --git a/lib/src/main/java/com/diffplug/spotless/npm/EslintConfig.java b/lib/src/main/java/com/diffplug/spotless/npm/EslintConfig.java index 8db9cf07af..79fda26180 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/EslintConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/EslintConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package com.diffplug.spotless.npm; import java.io.File; +import java.io.Serial; import java.io.Serializable; import javax.annotation.Nullable; @@ -23,6 +24,7 @@ import com.diffplug.spotless.FileSignature; public class EslintConfig implements Serializable { + @Serial private static final long serialVersionUID = 1L; @SuppressWarnings("unused") @@ -38,13 +40,11 @@ public EslintConfig withEslintConfigPath(@Nullable File eslintConfigPath) { return new EslintConfig(eslintConfigPath, this.eslintConfigJs); } - @Nullable - public File getEslintConfigPath() { + @Nullable public File getEslintConfigPath() { return eslintConfigPathSignature == null ? null : eslintConfigPathSignature.get().getOnlyFile(); } - @Nullable - public String getEslintConfigJs() { + @Nullable public String getEslintConfigJs() { return eslintConfigJs; } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java index 70beaf91ca..d85b4d7a8c 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -174,9 +174,9 @@ private void setConfigToCallOptions(Map eslintCallOptions) if (eslintConfig.getEslintConfigJs() != null) { eslintCallOptions.put(FormatOption.ESLINT_OVERRIDE_CONFIG, eslintConfig.getEslintConfigJs()); } - if (eslintConfig instanceof EslintTypescriptConfig) { + if (eslintConfig instanceof EslintTypescriptConfig config) { // if we are a ts config, see if we need to use specific paths or use default projectDir - File tsConfigFilePath = ((EslintTypescriptConfig) eslintConfig).getTypescriptConfigPath(); + File tsConfigFilePath = config.getTypescriptConfigPath(); File tsConfigRootDir = tsConfigFilePath != null ? tsConfigFilePath.getParentFile() : projectDir; eslintCallOptions.put(FormatOption.TS_CONFIG_ROOT_DIR, nodeModulesDir.getAbsoluteFile().toPath().relativize(tsConfigRootDir.getAbsoluteFile().toPath()).toString()); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/EslintTypescriptConfig.java b/lib/src/main/java/com/diffplug/spotless/npm/EslintTypescriptConfig.java index 42dec6837a..7b948ac370 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/EslintTypescriptConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/EslintTypescriptConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2022-2024 DiffPlug + * Copyright 2022-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,14 @@ package com.diffplug.spotless.npm; import java.io.File; +import java.io.Serial; import javax.annotation.Nullable; import com.diffplug.spotless.FileSignature; public class EslintTypescriptConfig extends EslintConfig { + @Serial private static final long serialVersionUID = 2L; @SuppressWarnings("unused") @@ -37,8 +39,7 @@ public EslintConfig withEslintConfigPath(@Nullable File eslintConfigPath) { return new EslintTypescriptConfig(eslintConfigPath, this.getEslintConfigJs(), getTypescriptConfigPath()); } - @Nullable - public File getTypescriptConfigPath() { + @Nullable public File getTypescriptConfigPath() { return typescriptConfigPathSignature == null ? null : this.typescriptConfigPathSignature.get().getOnlyFile(); } } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java b/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java index fce1497de6..d674621261 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2023 DiffPlug + * Copyright 2020-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,10 @@ import static java.util.Objects.requireNonNull; import java.io.File; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; @@ -43,8 +46,7 @@ Optional tryFind() { return fileCandidateFinders .stream() .map(Supplier::get) - .filter(Optional::isPresent) - .map(Optional::get) + .flatMap(Optional::stream) .findFirst(); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/JsonEscaper.java b/lib/src/main/java/com/diffplug/spotless/npm/JsonEscaper.java index 848dd030dd..ec4146742c 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/JsonEscaper.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/JsonEscaper.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,11 +28,11 @@ private JsonEscaper() { public static String jsonEscape(Object val) { requireNonNull(val); - if (val instanceof JsonRawValue) { - return jsonEscape((JsonRawValue) val); + if (val instanceof JsonRawValue value) { + return jsonEscape(value); } - if (val instanceof String) { - return jsonEscape((String) val); + if (val instanceof String string) { + return jsonEscape(string); } if (ListableAdapter.canAdapt(val)) { // create an array diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeExecutableResolver.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeExecutableResolver.java index eb30ae78b8..832bcd97a8 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeExecutableResolver.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeExecutableResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,8 @@ static Optional tryFindNextTo(File npmExecutable) { } public static String explainMessage() { - return "Spotless was unable to find a node executable.\n" + - "Either specify the node executable explicitly or make sure it can be found next to the npm executable."; + return """ + Spotless was unable to find a node executable. + Either specify the node executable explicitly or make sure it can be found next to the npm executable."""; } } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java index a821dd6b8e..390e515c5e 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java @@ -107,7 +107,7 @@ private String entryName() { @Override public String describe() { - return String.format("Wrapper around [%s] to cache node_modules in [%s]", actualNpmInstallProcess.describe(), cacheDir.getAbsolutePath()); + return "Wrapper around [%s] to cache node_modules in [%s]".formatted(actualNpmInstallProcess.describe(), cacheDir.getAbsolutePath()); } } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java index a6089c3972..1b8ec1c58e 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java @@ -52,7 +52,7 @@ private static String nodeModulesDirName(String packageJsonContent, String serve throw new IllegalArgumentException("package.json must contain a name property"); } String packageName = matcher.group(1); - return String.format("%s-node-modules-%s", packageName, md5Hash); + return "%s-node-modules-%s".formatted(packageName, md5Hash); } File nodeModulesDir() { @@ -103,8 +103,7 @@ public boolean isNodeModulesPrepared() { @Override public String toString() { - return String.format( - "NodeServerLayout[nodeModulesDir=%s, packageJsonFile=%s, serveJsFile=%s, npmrcFile=%s]", + return "NodeServerLayout[nodeModulesDir=%s, packageJsonFile=%s, serveJsFile=%s, npmrcFile=%s]".formatted( this.nodeModulesDir, this.packageJsonFile, this.serveJsFile, diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmConfig.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmConfig.java index 863be41193..c4ea1310f8 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.npm; +import java.io.Serial; import java.io.Serializable; import java.util.Objects; @@ -22,6 +23,7 @@ class NpmConfig implements Serializable { + @Serial private static final long serialVersionUID = 684264546497914877L; @Nonnull diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java index 8c233abc8c..4a06447407 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,14 +77,15 @@ static Optional tryFind() { } static String explainMessage() { - return "Spotless tries to find your npm executable automatically. It looks for npm in the following places:\n" + - "- An executable referenced by the java system property 'npm.exec' - if such a system property exists.\n" + - "- The environment variable 'NVM_BIN' - if such an environment variable exists.\n" + - "- The environment variable 'NVM_SYMLINK' - if such an environment variable exists.\n" + - "- The environment variable 'NODE_PATH' - if such an environment variable exists.\n" + - "- In your 'PATH' environment variable\n" + - "\n" + - "If autodiscovery fails for your system, try to set one of the environment variables correctly or\n" + - "try setting the system property 'npm.exec' in the build process to override autodiscovery."; + return """ + Spotless tries to find your npm executable automatically. It looks for npm in the following places: + - An executable referenced by the java system property 'npm.exec' - if such a system property exists. + - The environment variable 'NVM_BIN' - if such an environment variable exists. + - The environment variable 'NVM_SYMLINK' - if such an environment variable exists. + - The environment variable 'NODE_PATH' - if such an environment variable exists. + - In your 'PATH' environment variable + + If autodiscovery fails for your system, try to set one of the environment variables correctly or + try setting the system property 'npm.exec' in the build process to override autodiscovery."""; } } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepLocations.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepLocations.java index 4df5736dd9..7eb5a28350 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepLocations.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepLocations.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,12 +18,14 @@ import static java.util.Objects.requireNonNull; import java.io.File; +import java.io.Serial; import java.io.Serializable; import javax.annotation.Nonnull; class NpmFormatterStepLocations implements Serializable { + @Serial private static final long serialVersionUID = -1055408537924029969L; private final File projectDir; diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java index 9f27942abc..4571db9ea6 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java @@ -19,6 +19,7 @@ import java.io.File; import java.io.IOException; +import java.io.Serial; import java.io.Serializable; import java.time.Duration; import java.util.Collections; @@ -43,6 +44,7 @@ abstract class NpmFormatterStepStateBase implements Serializable { private static final TimedLogger timedLogger = TimedLogger.forLogger(logger); + @Serial private static final long serialVersionUID = 1460749955865959948L; private final String stepName; @@ -117,7 +119,7 @@ protected ServerProcessInfo npmRunServer() throws ServerStartException, IOExcept final UUID nodeServerInstanceId = UUID.randomUUID(); // The npm process will output the randomly selected port of the http server process to 'server-.port' file // so in order to be safe, remove such a file if it exists before starting. - final File serverPortFile = new File(this.nodeServerLayout.nodeModulesDir(), String.format("server-%s.port", nodeServerInstanceId)); + final File serverPortFile = new File(this.nodeServerLayout.nodeModulesDir(), "server-%s.port".formatted(nodeServerInstanceId)); NpmResourceHelper.deleteFileIfExists(serverPortFile); // start the http server in node server = nodeServeApp.startNpmServeProcess(nodeServerInstanceId); @@ -211,6 +213,7 @@ public void close() throws Exception { } protected static class ServerStartException extends RuntimeException { + @Serial private static final long serialVersionUID = -8803977379866483002L; public ServerStartException(String message, Throwable cause) { diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmPathResolver.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmPathResolver.java index f62340f074..75d17cd6e2 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmPathResolver.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmPathResolver.java @@ -16,12 +16,14 @@ package com.diffplug.spotless.npm; import java.io.File; +import java.io.Serial; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class NpmPathResolver implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final File explicitNpmExecutable; diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmProcessException.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmProcessException.java index c2e8444bcc..b0cddc2ffb 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmProcessException.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmProcessException.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,11 +15,14 @@ */ package com.diffplug.spotless.npm; +import java.io.Serial; + import javax.annotation.CheckForNull; import com.diffplug.spotless.ProcessRunner; public class NpmProcessException extends RuntimeException { + @Serial private static final long serialVersionUID = 6424331316676759525L; private final transient ProcessRunner.Result result; diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java index 3c146cd315..36e94892e4 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java @@ -15,11 +15,14 @@ */ package com.diffplug.spotless.npm; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.security.MessageDigest; import java.time.Duration; @@ -130,7 +133,7 @@ static File copyFileToDirAtSubpath(File file, File targetDir, String relativePat Objects.requireNonNull(relativePath); try { // create file pointing to relativePath in targetDir - final Path relativeTargetFile = Paths.get(targetDir.getAbsolutePath(), relativePath); + final Path relativeTargetFile = Path.of(targetDir.getAbsolutePath(), relativePath); assertDirectoryExists(relativeTargetFile.getParent().toFile()); Files.copy(file.toPath(), relativeTargetFile, StandardCopyOption.REPLACE_EXISTING); @@ -157,7 +160,7 @@ static String md5(String fileContent, String... additionalFileContents) { // convert byte array digest to hex string StringBuilder sb = new StringBuilder(); for (byte b : digest) { - sb.append(String.format("%02x", b & 0xff)); + sb.append("%02x".formatted(b & 0xff)); } return sb.toString(); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/PrettierConfig.java b/lib/src/main/java/com/diffplug/spotless/npm/PrettierConfig.java index 8a51910205..956de348dc 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package com.diffplug.spotless.npm; import java.io.File; +import java.io.Serial; import java.io.Serializable; import java.util.Map; import java.util.TreeMap; @@ -26,6 +27,7 @@ public class PrettierConfig implements Serializable { + @Serial private static final long serialVersionUID = -8709340269833126583L; private final FileSignature.Promised prettierConfigPathSignature; @@ -37,8 +39,7 @@ public PrettierConfig(@Nullable File prettierConfigPath, @Nullable Map() : new TreeMap<>(options); } - @Nullable - public File getPrettierConfigPath() { + @Nullable public File getPrettierConfigPath() { return prettierConfigPathSignature == null ? null : prettierConfigPathSignature.get().getOnlyFile(); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java b/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java index 9728b61eec..c17812ddda 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package com.diffplug.spotless.npm; import java.io.File; +import java.io.Serial; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -28,6 +29,7 @@ import com.diffplug.spotless.Lint; class PrettierMissingParserException extends RuntimeException implements Lint.Has { + @Serial private static final long serialVersionUID = 1L; private static final Map EXTENSIONS_TO_PLUGINS; @@ -100,7 +102,7 @@ private static String recommendPlugin(File file) { return "A good candidate for file '" + file + "' is '" + pluginName + "\n" + "See if you can find it on \n" + "or search on npmjs.com for a plugin matching that name: " - + String.format("", pluginName) + + "".formatted(pluginName) + "\n\n" + "For instructions on how to include plugins for prettier in spotless see our documentation:\n" + "- for Gradle \n" diff --git a/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java b/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java index 3182d81fbb..6adf3a28dd 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; @@ -108,11 +107,11 @@ public File getEntry(String key, String fileName) { } private File entry(String key, String origName) { - return Paths.get(shadowCopyRoot().getAbsolutePath(), key, origName).toFile(); + return Path.of(shadowCopyRoot().getAbsolutePath(), key, origName).toFile(); } public File copyEntryInto(String key, String origName, File targetParentFolder) { - File target = Paths.get(targetParentFolder.getAbsolutePath(), origName).toFile(); + File target = Path.of(targetParentFolder.getAbsolutePath(), origName).toFile(); if (target.exists()) { logger.warn("Shadow copy destination already exists, deleting! {}: {}", key, target); ThrowingEx.run(() -> Files.walkFileTree(target.toPath(), new DeleteDirectoryRecursively())); diff --git a/lib/src/main/java/com/diffplug/spotless/npm/SimpleRestClient.java b/lib/src/main/java/com/diffplug/spotless/npm/SimpleRestClient.java index 2f413e4b3a..1328ec318f 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/SimpleRestClient.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/SimpleRestClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -135,7 +135,7 @@ public String getExceptionMessage() { @Override public String getMessage() { - return String.format("%s [HTTP %s] -- (%s)", getExceptionMessage(), getStatusCode(), getResponseMessage()); + return "%s [HTTP %s] -- (%s)".formatted(getExceptionMessage(), getStatusCode(), getResponseMessage()); } } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/StandardNpmProcessFactory.java b/lib/src/main/java/com/diffplug/spotless/npm/StandardNpmProcessFactory.java index b9abd03029..8ca7246221 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/StandardNpmProcessFactory.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/StandardNpmProcessFactory.java @@ -75,7 +75,7 @@ protected ProcessRunner.LongRunningProcess doStart() { protected abstract String describe(); public String doDescribe() { - return String.format("%s in %s [%s]", getClass().getSimpleName(), workingDir, String.join(" ", commandLine())); + return "%s in %s [%s]".formatted(getClass().getSimpleName(), workingDir, String.join(" ", commandLine())); } } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java index b171b0ca7f..f013a255e6 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,9 @@ import java.io.File; import java.io.IOException; import java.io.Serializable; -import java.util.*; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -68,8 +70,7 @@ public static class State extends NpmFormatterStepStateBase implements Serializa private final File buildDir; - @Nullable - private final TypedTsFmtConfigFile configFile; + @Nullable private final TypedTsFmtConfigFile configFile; public State(String stepName, Map versions, File projectDir, File buildDir, File cacheDir, NpmPathResolver npmPathResolver, @Nullable TypedTsFmtConfigFile configFile, @Nullable Map inlineTsFmtSettings) throws IOException { super(stepName, diff --git a/lib/src/main/java/com/diffplug/spotless/npm/TypedTsFmtConfigFile.java b/lib/src/main/java/com/diffplug/spotless/npm/TypedTsFmtConfigFile.java index c9b80394a8..013e810370 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/TypedTsFmtConfigFile.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/TypedTsFmtConfigFile.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,11 +18,13 @@ import static java.util.Objects.requireNonNull; import java.io.File; +import java.io.Serial; import java.io.Serializable; import java.util.Locale; public class TypedTsFmtConfigFile implements Serializable { + @Serial private static final long serialVersionUID = -4442310349275775501L; private final TsConfigFileType configFileType; diff --git a/lib/src/main/java/com/diffplug/spotless/pom/SortPomCfg.java b/lib/src/main/java/com/diffplug/spotless/pom/SortPomCfg.java index db37ae25fd..15bb77fee2 100644 --- a/lib/src/main/java/com/diffplug/spotless/pom/SortPomCfg.java +++ b/lib/src/main/java/com/diffplug/spotless/pom/SortPomCfg.java @@ -15,10 +15,12 @@ */ package com.diffplug.spotless.pom; +import java.io.Serial; import java.io.Serializable; // Class and members must be public, otherwise we get failed to access class com.diffplug.spotless.pom.SortPomInternalState from class com.diffplug.spotless.pom.SortPomFormatterFunc (com.diffplug.spotless.pom.SortPomInternalState is in unnamed module of loader org.codehaus.plexus.classworlds.realm.ClassRealm @682bd3c4; com.diffplug.spotless.pom.SortPomFormatterFunc is in unnamed module of loader com.diffplug.spotless.pom.DelegatingClassLoader @573284a5) public class SortPomCfg implements Serializable { + @Serial private static final long serialVersionUID = 1L; public String version = "4.0.0"; diff --git a/lib/src/main/java/com/diffplug/spotless/pom/SortPomStep.java b/lib/src/main/java/com/diffplug/spotless/pom/SortPomStep.java index b082c021c4..e4c658f855 100644 --- a/lib/src/main/java/com/diffplug/spotless/pom/SortPomStep.java +++ b/lib/src/main/java/com/diffplug/spotless/pom/SortPomStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.pom; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -25,6 +26,7 @@ import com.diffplug.spotless.Provisioner; public class SortPomStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATE = "com.github.ekryd.sortpom:sortpom-sorter:"; public static final String NAME = "sortPom"; @@ -49,6 +51,7 @@ private State equalityState() { } private static class State implements Serializable { + @Serial private static final long serialVersionUID = 1; private final SortPomCfg cfg; diff --git a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterConfig.java b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterConfig.java index 13c5bfcaa4..9e9f62d408 100644 --- a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,12 @@ */ package com.diffplug.spotless.rdf; +import java.io.Serial; import java.io.Serializable; import java.util.Objects; public class RdfFormatterConfig implements Serializable { + @Serial private static final long serialVersionUID = 1L; private boolean failOnWarning = true; private String turtleFormatterVersion = RdfFormatterStep.LATEST_TURTLE_FORMATTER_VERSION; diff --git a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterFunc.java b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterFunc.java index 03665b69a2..83e8775edf 100644 --- a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterFunc.java +++ b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterFunc.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,11 +51,11 @@ public String apply(String rawUnix, File file) throws Exception { int lastDot = filename.lastIndexOf('.'); if (lastDot < 0) { throw new IllegalArgumentException( - String.format("File %s has no file extension, cannot determine RDF format", file.getAbsolutePath())); + "File %s has no file extension, cannot determine RDF format".formatted(file.getAbsolutePath())); } if (lastDot + 1 >= filename.length()) { throw new IllegalArgumentException( - String.format("File %s has no file extension, cannot determine RDF format", file.getAbsolutePath())); + "File %s has no file extension, cannot determine RDF format".formatted(file.getAbsolutePath())); } String extension = filename.substring(lastDot + 1); @@ -72,7 +72,7 @@ public String apply(String rawUnix, File file) throws Exception { if (NQUADS_EXTENSIONS.contains(extension)) { return formatNQuads(rawUnix, file); } - throw new IllegalArgumentException(String.format("Cannot handle file with extension %s", extension)); + throw new IllegalArgumentException("Cannot handle file with extension %s".formatted(extension)); } catch (InvocationTargetException e) { throw new RuntimeException("Error formatting file " + file.getPath(), e.getCause()); } catch (Exception e) { @@ -113,8 +113,8 @@ private static void veryfyResult(String rawUnix, File file, ReflectionHelper ref long afterSize = reflectionHelper.modelSize(modelAfter); String diffResult; if (beforeSize != afterSize) { - diffResult = String.format("< %,d triples", beforeSize); - diffResult += String.format("> %,d triples", afterSize); + diffResult = "< %,d triples".formatted(beforeSize); + diffResult += "> %,d triples".formatted(afterSize); } else { diffResult = calculateDiff(reflectionHelper, modelBefore, modelAfter); } @@ -153,9 +153,9 @@ private static String calculateDiff(ReflectionHelper reflectionHelper, Object mo }) .collect(Collectors.toList()); if (!(onlyInBeforeContent.isEmpty() && onlyInAfterContent.isEmpty())) { - diffResult = onlyInBeforeContent.stream().map(s -> String.format("< %s", s)) + diffResult = onlyInBeforeContent.stream().map(s -> "< %s".formatted(s)) .collect(Collectors.joining("\n")); - diffResult += "\n" + onlyInAfterContent.stream().map(s -> String.format("> %s", s)).collect(Collectors.joining("\n")); + diffResult += "\n" + onlyInAfterContent.stream().map(s -> "> %s".formatted(s)).collect(Collectors.joining("\n")); } else { diffResult = "'before' and 'after' content differs, but we don't know why. This is probably a bug."; } diff --git a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterStep.java index a5ed70bfed..0c5b21d66d 100644 --- a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.rdf; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.Map; @@ -27,6 +28,7 @@ public class RdfFormatterStep implements Serializable { public static final String LATEST_TURTLE_FORMATTER_VERSION = "1.2.13"; + @Serial private static final long serialVersionUID = 1L; private static final String TURTLE_FORMATTER_COORDINATES = "de.atextor:turtle-formatter"; @@ -60,6 +62,7 @@ public RdfFormatterStep(JarState.Promised jarState, RdfFormatterConfig config, } public static class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final RdfFormatterConfig config; diff --git a/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java b/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java index 435e9757af..1979f99a1f 100644 --- a/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -209,7 +209,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl + "the presence of warnings, set the configuration parameter 'failOnWarning' to 'false' (default: 'true')"); } throw new RuntimeException( - String.format("line %d, col %d: %s (severity: %s)", line, col, message, severity)); + "line %d, col %d: %s (severity: %s)".formatted(line, col, message, severity)); } return null; } @@ -303,7 +303,7 @@ private void callBuilderMethod(Object builder, Method method, String parameterVa Collectors.toList()); if (selectedEnumValueList.isEmpty()) { throw new IllegalArgumentException( - String.format("Cannot set config option %s to value %s: value must be one of %s", + "Cannot set config option %s to value %s: value must be one of %s".formatted( method.getName(), parameterValueAsString, Arrays.stream(param.getEnumConstants()).map(e -> { @@ -316,7 +316,7 @@ private void callBuilderMethod(Object builder, Method method, String parameterVa Collectors.joining(",", "[", "]")))); } else if (selectedEnumValueList.size() > 1) { throw new IllegalArgumentException( - String.format("Found more than 1 enum value for name %s, that should never happen", + "Found more than 1 enum value for name %s, that should never happen".formatted( parameterValueAsString)); } method.invoke(builder, selectedEnumValueList.get(0)); @@ -339,8 +339,7 @@ private void callBuilderMethod(Object builder, Method method, String parameterVa } else if (List.class.isAssignableFrom(param)) { method.invoke(builder, makeListOf(((ParameterizedType) method.getGenericParameterTypes()[0]).getActualTypeArguments()[0], parameterValueAsString)); } else { - throw new IllegalArgumentException(String.format( - "Cannot handle turtle-formatter config option %s: parameters of type %s are not implemented in the spotless plugin yet", + throw new IllegalArgumentException("Cannot handle turtle-formatter config option %s: parameters of type %s are not implemented in the spotless plugin yet".formatted( method.getName(), param.getName())); } } @@ -398,7 +397,7 @@ private Object instantiate(Type type, String stringRepresentation) if (type.equals(TurtleFormatKnownPrefix)) { return getKnownPrefix(stringRepresentation); } - throw new IllegalArgumentException(String.format("Cannot instantiate class %s from string representation %s", type, stringRepresentation)); + throw new IllegalArgumentException("Cannot instantiate class %s from string representation %s".formatted(type, stringRepresentation)); } private String tryToMakeUri(String stringRepresentation) @@ -430,7 +429,7 @@ private Object getKnownPrefix(String stringRepresentation) } } } - throw new IllegalArgumentException(String.format("Unable to find FormattingStyle.KnownPrefix for prefix '%s'. Options are: %s", stringRepresentation, options.stream().collect( + throw new IllegalArgumentException("Unable to find FormattingStyle.KnownPrefix for prefix '%s'. Options are: %s".formatted(stringRepresentation, options.stream().collect( Collectors.joining(",\n\t", "\n\t", "\n")))); } @@ -451,18 +450,18 @@ private Method getBuilderMethod(String optionName) { .sorted(Comparator.comparing(Method::getName)).collect( Collectors.toList()); throw new RuntimeException( - String.format("Unrecognized configuration parameter name: %s. Candidates are:%n%s", optionName, candidates.stream().map(Method::getName).collect( + "Unrecognized configuration parameter name: %s. Candidates are:%n%s".formatted(optionName, candidates.stream().map(Method::getName).collect( Collectors.joining("\n\t", "\t", "")))); } if (methods.size() > 1) { throw new RuntimeException( - String.format("More than one builder method found for configuration parameter name: %s", + "More than one builder method found for configuration parameter name: %s".formatted( optionName)); } Method method = methods.get(0); if (method.getParameterCount() != 1) { throw new RuntimeException( - String.format("Method with unexpected parameter count %s found for configuration parameter name: %s", + "Method with unexpected parameter count %s found for configuration parameter name: %s".formatted( method.getParameterCount(), optionName)); } diff --git a/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java b/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java index 9a2ec248ee..32378db4db 100644 --- a/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java +++ b/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ import java.io.File; import java.io.IOException; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.util.Collections; @@ -31,6 +32,7 @@ /** Wraps up scalafmt as a FormatterStep. */ public class ScalaFmtStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; static final String DEFAULT_VERSION = "3.8.1"; @@ -40,8 +42,7 @@ public class ScalaFmtStep implements Serializable { private static final String MAVEN_COORDINATE = "org.scalameta:scalafmt-core_"; private final JarState.Promised jarState; - @Nullable - private final File configFile; + @Nullable private final File configFile; private ScalaFmtStep(JarState.Promised jarState, @Nullable File configFile) { this.jarState = jarState; @@ -78,6 +79,7 @@ private State equalityState() throws IOException { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final JarState jarState; diff --git a/lib/src/main/java/com/diffplug/spotless/shell/ShfmtStep.java b/lib/src/main/java/com/diffplug/spotless/shell/ShfmtStep.java index 6630bf32a1..9e3feba31e 100644 --- a/lib/src/main/java/com/diffplug/spotless/shell/ShfmtStep.java +++ b/lib/src/main/java/com/diffplug/spotless/shell/ShfmtStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,14 +64,14 @@ public FormatterStep create() { } private RoundtripState createRoundtrip() throws IOException, InterruptedException { - String howToInstall = "" + - "You can download shfmt from https://github.com/mvdan/sh and " + - "then point Spotless to it with {@code pathToExe('/path/to/shfmt')} " + - "or you can use your platform's package manager:" + - "\n win: choco install shfmt" + - "\n mac: brew install shfmt" + - "\n linux: apt install shfmt" + - "\n github issue to handle this better: https://github.com/diffplug/spotless/issues/673"; + String howToInstall = """ + You can download shfmt from https://github.com/mvdan/sh and \ + then point Spotless to it with {@code pathToExe('/path/to/shfmt')} \ + or you can use your platform's package manager: + win: choco install shfmt + mac: brew install shfmt + linux: apt install shfmt + github issue to handle this better: https://github.com/diffplug/spotless/issues/673"""; final ForeignExe exe = ForeignExe.nameAndVersion("shfmt", version) .pathToExe(pathToExe) .versionRegex(Pattern.compile("([\\d.]+)")) diff --git a/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlConfig.java b/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlConfig.java index 166ee5f307..072aa401c9 100644 --- a/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.yaml; +import java.io.Serial; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; @@ -25,6 +26,7 @@ * Specialization of {@link JacksonConfig} for YAML documents */ public class JacksonYamlConfig extends JacksonConfig { + @Serial private static final long serialVersionUID = 1L; protected Map yamlFeatureToToggle = new LinkedHashMap<>(); diff --git a/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlStep.java b/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlStep.java index 45c961b2e6..58ffea7816 100644 --- a/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlStep.java +++ b/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.yaml; +import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -31,6 +32,7 @@ // https://stackoverflow.com/questions/14515994/convert-json-string-to-pretty-print-json-output-using-jackson // https://stackoverflow.com/questions/60891174/i-want-to-load-a-yaml-file-possibly-edit-the-data-and-then-dump-it-again-how public class JacksonYamlStep implements Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATE = "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:"; private static final String DEFAULT_VERSION = "2.14.1"; @@ -68,6 +70,7 @@ private State equalityState() { } private static final class State implements Serializable { + @Serial private static final long serialVersionUID = 1L; private final JacksonYamlConfig jacksonConfig; diff --git a/lib/src/main/java/com/diffplug/spotless/yaml/SerializeToByteArrayHack.java b/lib/src/main/java/com/diffplug/spotless/yaml/SerializeToByteArrayHack.java index c63b6d918b..6074a78273 100644 --- a/lib/src/main/java/com/diffplug/spotless/yaml/SerializeToByteArrayHack.java +++ b/lib/src/main/java/com/diffplug/spotless/yaml/SerializeToByteArrayHack.java @@ -16,6 +16,7 @@ package com.diffplug.spotless.yaml; import java.io.File; +import java.io.Serial; import javax.annotation.Nullable; @@ -37,6 +38,7 @@ * problems with up-to-dateness, then adding this step can be a workaround. */ public class SerializeToByteArrayHack implements FormatterStep { + @Serial private static final long serialVersionUID = 8071047581828362545L; @Override @@ -44,8 +46,7 @@ public String getName() { return "hack to force serializing objects to byte array"; } - @Nullable - @Override + @Nullable @Override public String format(String rawUnix, File file) throws Exception { return null; } diff --git a/lib/src/test/java/com/diffplug/spotless/npm/NodeServerLayoutTest.java b/lib/src/test/java/com/diffplug/spotless/npm/NodeServerLayoutTest.java index f2cb55943d..ccb5e51caa 100644 --- a/lib/src/test/java/com/diffplug/spotless/npm/NodeServerLayoutTest.java +++ b/lib/src/test/java/com/diffplug/spotless/npm/NodeServerLayoutTest.java @@ -68,7 +68,7 @@ void itCalculatesDifferentNodeModulesDirForDifferentServeJs() throws IOException static String prettierPackageJson(Map dependencies) { String templateContent = NpmResourceHelper.readUtf8StringFromClasspath(NodeServerLayoutTest.class, "/com/diffplug/spotless/npm/prettier-package.json"); String dependenciesList = dependencies.entrySet().stream() - .map(entry -> String.format("\"%s\": \"%s\"", entry.getKey(), entry.getValue())) + .map(entry -> "\"%s\": \"%s\"".formatted(entry.getKey(), entry.getValue())) .reduce((a, b) -> a + ",\n " + b) .orElse(""); diff --git a/lib/src/testCompatKtLint0Dot48Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot48Dot0AdapterTest.java b/lib/src/testCompatKtLint0Dot48Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot48Dot0AdapterTest.java index f9c19d69a7..97278f9ffb 100644 --- a/lib/src/testCompatKtLint0Dot48Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot48Dot0AdapterTest.java +++ b/lib/src/testCompatKtLint0Dot48Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot48Dot0AdapterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; @@ -34,7 +33,7 @@ public class KtLintCompat0Dot48Dot0AdapterTest { public void testDefaults(@TempDir Path path) throws IOException { KtLintCompat0Dot48Dot0Adapter ktLintCompat0Dot48Dot0Adapter = new KtLintCompat0Dot48Dot0Adapter(); var content = loadAndWriteText(path, "empty_class_body.kt"); - final Path filePath = Paths.get(path.toString(), "empty_class_body.kt"); + final Path filePath = Path.of(path.toString(), "empty_class_body.kt"); Map editorConfigOverrideMap = new HashMap<>(); @@ -46,7 +45,7 @@ public void testDefaults(@TempDir Path path) throws IOException { public void testEditorConfigCanDisable(@TempDir Path path) throws IOException { KtLintCompat0Dot48Dot0Adapter ktLintCompat0Dot48Dot0Adapter = new KtLintCompat0Dot48Dot0Adapter(); var content = loadAndWriteText(path, "fails_no_semicolons.kt"); - final Path filePath = Paths.get(path.toString(), "fails_no_semicolons.kt"); + final Path filePath = Path.of(path.toString(), "fails_no_semicolons.kt"); Map editorConfigOverrideMap = new HashMap<>(); editorConfigOverrideMap.put("indent_style", "tab"); diff --git a/lib/src/testCompatKtLint0Dot49Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot49Dot0AdapterTest.java b/lib/src/testCompatKtLint0Dot49Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot49Dot0AdapterTest.java index 27d085f7fd..faa95c938c 100644 --- a/lib/src/testCompatKtLint0Dot49Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot49Dot0AdapterTest.java +++ b/lib/src/testCompatKtLint0Dot49Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot49Dot0AdapterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; @@ -34,7 +33,7 @@ public class KtLintCompat0Dot49Dot0AdapterTest { public void testDefaults(@TempDir Path path) throws IOException { KtLintCompat0Dot49Dot0Adapter ktLintCompat0Dot49Dot0Adapter = new KtLintCompat0Dot49Dot0Adapter(); var content = loadAndWriteText(path, "EmptyClassBody.kt"); - final Path filePath = Paths.get(path.toString(), "EmptyClassBody.kt"); + final Path filePath = Path.of(path.toString(), "EmptyClassBody.kt"); Map editorConfigOverrideMap = new HashMap<>(); @@ -46,7 +45,7 @@ public void testDefaults(@TempDir Path path) throws IOException { public void testEditorConfigCanDisable(@TempDir Path path) throws IOException { KtLintCompat0Dot49Dot0Adapter ktLintCompat0Dot49Dot0Adapter = new KtLintCompat0Dot49Dot0Adapter(); var content = loadAndWriteText(path, "FailsNoSemicolons.kt"); - final Path filePath = Paths.get(path.toString(), "FailsNoSemicolons.kt"); + final Path filePath = Path.of(path.toString(), "FailsNoSemicolons.kt"); Map editorConfigOverrideMap = new HashMap<>(); editorConfigOverrideMap.put("indent_style", "tab"); diff --git a/lib/src/testCompatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0AdapterTest.java b/lib/src/testCompatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0AdapterTest.java index 27dce68f09..ccb5e931db 100644 --- a/lib/src/testCompatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0AdapterTest.java +++ b/lib/src/testCompatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0AdapterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; @@ -34,7 +33,7 @@ public class KtLintCompat0Dot50Dot0AdapterTest { public void testDefaults(@TempDir Path path) throws IOException { KtLintCompat0Dot50Dot0Adapter KtLintCompat0Dot50Dot0Adapter = new KtLintCompat0Dot50Dot0Adapter(); var content = loadAndWriteText(path, "EmptyClassBody.kt"); - final Path filePath = Paths.get(path.toString(), "EmptyClassBody.kt"); + final Path filePath = Path.of(path.toString(), "EmptyClassBody.kt"); Map editorConfigOverrideMap = new HashMap<>(); @@ -46,7 +45,7 @@ public void testDefaults(@TempDir Path path) throws IOException { public void testEditorConfigCanDisable(@TempDir Path path) throws IOException { KtLintCompat0Dot50Dot0Adapter KtLintCompat0Dot50Dot0Adapter = new KtLintCompat0Dot50Dot0Adapter(); var content = loadAndWriteText(path, "FailsNoSemicolons.kt"); - final Path filePath = Paths.get(path.toString(), "FailsNoSemicolons.kt"); + final Path filePath = Path.of(path.toString(), "FailsNoSemicolons.kt"); Map editorConfigOverrideMap = new HashMap<>(); editorConfigOverrideMap.put("indent_style", "tab"); diff --git a/lib/src/testCompatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0AdapterTest.java b/lib/src/testCompatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0AdapterTest.java index 760aa89ae5..4792e278d0 100644 --- a/lib/src/testCompatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0AdapterTest.java +++ b/lib/src/testCompatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0AdapterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; @@ -34,7 +33,7 @@ public class KtLintCompat1Dot0Dot0AdapterTest { public void testDefaults(@TempDir Path path) throws IOException { KtLintCompat1Dot0Dot0Adapter KtLintCompat1Dot0Dot0Adapter = new KtLintCompat1Dot0Dot0Adapter(); var content = loadAndWriteText(path, "EmptyClassBody.kt"); - final Path filePath = Paths.get(path.toString(), "EmptyClassBody.kt"); + final Path filePath = Path.of(path.toString(), "EmptyClassBody.kt"); Map editorConfigOverrideMap = new HashMap<>(); @@ -46,7 +45,7 @@ public void testDefaults(@TempDir Path path) throws IOException { public void testEditorConfigCanDisable(@TempDir Path path) throws IOException { KtLintCompat1Dot0Dot0Adapter KtLintCompat1Dot0Dot0Adapter = new KtLintCompat1Dot0Dot0Adapter(); var content = loadAndWriteText(path, "FailsNoSemicolons.kt"); - final Path filePath = Paths.get(path.toString(), "FailsNoSemicolons.kt"); + final Path filePath = Path.of(path.toString(), "FailsNoSemicolons.kt"); Map editorConfigOverrideMap = new HashMap<>(); editorConfigOverrideMap.put("indent_style", "tab"); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BiomeStepConfig.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BiomeStepConfig.java index 4767e5112a..69932670ac 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BiomeStepConfig.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BiomeStepConfig.java @@ -18,7 +18,7 @@ import static java.util.Objects.requireNonNull; import java.io.File; -import java.nio.file.Paths; +import java.nio.file.Path; import java.util.function.Consumer; import javax.annotation.Nullable; @@ -227,7 +227,7 @@ private BiomeStep newBuilder() { * @return The resolved path to the Biome executable. */ private String resolvePathToExe() { - var fileNameOnly = pathToExe instanceof String && Paths.get(pathToExe.toString()).getNameCount() == 1; + var fileNameOnly = pathToExe instanceof String && Path.of(pathToExe.toString()).getNameCount() == 1; if (fileNameOnly) { return pathToExe.toString(); } else { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FormatExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FormatExtension.java index 869999c071..2f319ef56b 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FormatExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FormatExtension.java @@ -306,14 +306,13 @@ protected final FileCollection parseTarget(Object target) { } private final FileCollection parseTargetIsExclude(Object target, boolean isExclude) { - if (target instanceof Collection) { - return parseTargetsIsExclude(((Collection) target).toArray(), isExclude); + if (target instanceof Collection collection) { + return parseTargetsIsExclude(collection.toArray(), isExclude); } else if (target instanceof FileCollection) { return (FileCollection) target; - } else if (target instanceof String) { + } else if (target instanceof String targetString) { File dir = getProject().getProjectDir(); ConfigurableFileTree matchedFiles = getProject().fileTree(dir); - String targetString = (String) target; matchedFiles.include(targetString); // since people are likely to do '**/*.md', we want to make sure to exclude diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GradleProvisioner.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GradleProvisioner.java index 4f5da6cd95..dbe9625c38 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GradleProvisioner.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GradleProvisioner.java @@ -163,8 +163,7 @@ public int hashCode() { public boolean equals(Object obj) { if (this == obj) { return true; - } else if (obj instanceof Request) { - Request o = (Request) obj; + } else if (obj instanceof Request o) { return o.withTransitives == withTransitives && o.mavenCoords.equals(mavenCoords); } else { return false; diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessDiagnoseTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessDiagnoseTask.java index 68f6e63e75..8ef7394c7b 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessDiagnoseTask.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessDiagnoseTask.java @@ -19,7 +19,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Locale; import org.gradle.api.DefaultTask; @@ -59,7 +58,7 @@ public void performAction() throws IOException { Path relative = srcRoot.relativize(file.toPath()); Path diagnoseFile = diagnoseRoot.resolve(relative); for (int i = 0; i < padded.steps().size(); ++i) { - Path path = Paths.get(diagnoseFile + "." + padded.type().name().toLowerCase(Locale.ROOT) + i); + Path path = Path.of(diagnoseFile + "." + padded.type().name().toLowerCase(Locale.ROOT) + i); Files.createDirectories(path.getParent()); String version = padded.steps().get(i); Files.write(path, version.getBytes(formatter.getEncoding())); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessInstallPrePushHookTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessInstallPrePushHookTask.java index 6717f121a8..6cd3d15458 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessInstallPrePushHookTask.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessInstallPrePushHookTask.java @@ -65,17 +65,17 @@ public void performAction() throws Exception { final var logger = new GitPreHookLogger() { @Override public void info(String format, Object... arguments) { - getLogger().lifecycle(String.format(format, arguments)); + getLogger().lifecycle(format.formatted(arguments)); } @Override public void warn(String format, Object... arguments) { - getLogger().warn(String.format(format, arguments)); + getLogger().warn(format.formatted(arguments)); } @Override public void error(String format, Object... arguments) { - getLogger().error(String.format(format, arguments)); + getLogger().error(format.formatted(arguments)); } }; diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskImpl.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskImpl.java index d3b96bf6e3..450a205425 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskImpl.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskImpl.java @@ -151,7 +151,7 @@ void processInputFile(@Nullable GitRatchet ratchet, Formatter formatter, File in // Need to copy the original file to the tmp location just to remember the file attributes Files.copy(input.toPath(), cleanFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); - getLogger().info(String.format("Writing clean file: %s", cleanFile)); + getLogger().info("Writing clean file: %s".formatted(cleanFile)); lintState.getDirtyState().writeCanonicalTo(cleanFile); } if (!lintState.isHasLints()) { diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java index 95f428fc00..ac84424eb6 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java @@ -185,7 +185,7 @@ void multipleFiles() throws Exception { void manyFiles() throws Exception { List testFiles = new ArrayList<>(); for (int i = 0; i < 9 + DiffMessageFormatter.MAX_FILES_TO_LIST - 1; ++i) { - String fileName = String.format("%02d", i) + ".txt"; + String fileName = "%02d".formatted(i) + ".txt"; testFiles.add(setFile(fileName).toContent("1\r\n2\r\n")); } Bundle spotless = create(testFiles); @@ -259,7 +259,7 @@ void manyFiles() throws Exception { void manyManyFiles() throws Exception { List testFiles = new ArrayList<>(); for (int i = 0; i < 9 + DiffMessageFormatter.MAX_FILES_TO_LIST; ++i) { - String fileName = String.format("%02d", i) + ".txt"; + String fileName = "%02d".formatted(i) + ".txt"; testFiles.add(setFile(fileName).toContent("1\r\n2\r\n")); } Bundle spotless = create(testFiles); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIncrementalResolutionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIncrementalResolutionTest.java index 6235c246bd..69360b74ef 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIncrementalResolutionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIncrementalResolutionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,16 +57,18 @@ void failureDoesntTriggerAll() throws IOException { // check will run against all three the first time. checkRanAgainst("abc"); // Subsequent runs will use the cached error message - checkRanAgainstNoneButError().contains("> The following files had format violations:\n" + - " b.md\n" + - " @@ -1 +1 @@\n" + - " -B\n" + - " +b"); - checkRanAgainstNoneButError().contains("> The following files had format violations:\n" + - " b.md\n" + - " @@ -1 +1 @@\n" + - " -B\n" + - " +b"); + checkRanAgainstNoneButError().contains(""" + > The following files had format violations: + b.md + @@ -1 +1 @@ + -B + +b"""); + checkRanAgainstNoneButError().contains(""" + > The following files had format violations: + b.md + @@ -1 +1 @@ + -B + +b"""); // apply will simply copy outputs the first time: no formatters executed applyRanAgainst(""); // the second time, it will only run on the file that was changed by apply @@ -79,11 +81,12 @@ void failureDoesntTriggerAll() throws IOException { // then check runs against just the changed file checkRanAgainst("a"); // even after failing once the error is still there - checkRanAgainstNoneButError().contains("> The following files had format violations:\n" + - " a.md\n" + - " @@ -1 +1 @@\n" + - " -A\n" + - " +a"); + checkRanAgainstNoneButError().contains(""" + > The following files had format violations: + a.md + @@ -1 +1 @@ + -A + +a"""); // and so does apply applyRanAgainst(); applyRanAgainst("a"); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/LicenseHeaderTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/LicenseHeaderTest.java index d4c01cdc6d..a8ac2dd9cc 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/LicenseHeaderTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/LicenseHeaderTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,8 +89,9 @@ void filterByContentPatternTest() throws IOException { setFile(TEST_JAVA).toContent(CONTENT); gradleRunner().withArguments("spotlessApply", "--stacktrace").forwardOutput().build(); assertFile(TEST_JAVA).hasContent("/** New License Header */\n" + CONTENT); - String multipleLicenseHeaderConfiguration = "licenseHeader('/** Base License Header */').named('PrimaryHeaderLicense').onlyIfContentMatches('Best')\n" + - "licenseHeader('/** Alternate License Header */').named('SecondaryHeaderLicense').onlyIfContentMatches('.*Test.+')"; + String multipleLicenseHeaderConfiguration = """ + licenseHeader('/** Base License Header */').named('PrimaryHeaderLicense').onlyIfContentMatches('Best') + licenseHeader('/** Alternate License Header */').named('SecondaryHeaderLicense').onlyIfContentMatches('.*Test.+')"""; setLicenseStep(multipleLicenseHeaderConfiguration); setFile(TEST_JAVA).toContent("/** 2003 */\n" + CONTENT); gradleRunner().withArguments("spotlessApply", "--stacktrace").forwardOutput().build(); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/NpmInstallCacheIntegrationTests.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/NpmInstallCacheIntegrationTests.java index e7ad5f1654..46d0817fcd 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/NpmInstallCacheIntegrationTests.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/NpmInstallCacheIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ import java.io.File; import java.io.IOException; -import java.nio.file.Paths; +import java.nio.file.Path; import org.assertj.core.api.Assertions; import org.gradle.testkit.runner.BuildResult; @@ -54,7 +54,7 @@ void prettierCachesNodeModulesToADefaultFolderWhenCachingEnabled() throws IOExce Assertions.assertThat(result.getOutput()) .doesNotContain("Using cached node_modules for") .contains("Caching node_modules for ") - .contains(Paths.get(dir1.getAbsolutePath(), "build", SPOTLESS_NPM_INSTALL_CACHE_DEFAULT_NAME).toString()); + .contains(Path.of(dir1.getAbsolutePath(), "build", SPOTLESS_NPM_INSTALL_CACHE_DEFAULT_NAME).toString()); } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessTaskImplTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessTaskImplTest.java index a1f49c7373..ad2ae7c5aa 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessTaskImplTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessTaskImplTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package com.diffplug.gradle.spotless; import java.io.File; -import java.nio.file.Paths; +import java.nio.file.Path; import org.assertj.core.api.Assertions; import org.gradle.api.file.DirectoryProperty; @@ -32,13 +32,13 @@ public void testThrowsMessageContainsFilename() throws Exception { SpotlessTaskImpl task = Mockito.mock(SpotlessTaskImpl.class, Mockito.CALLS_REAL_METHODS); Mockito.when(task.getLogger()).thenReturn(Mockito.mock(Logger.class)); - File projectDir = Paths.get("unitTests", "projectDir").toFile(); + File projectDir = Path.of("unitTests", "projectDir").toFile(); DirectoryProperty projectDirProperty = Mockito.mock(DirectoryProperty.class, Mockito.RETURNS_DEEP_STUBS); Mockito.when(projectDirProperty.get().getAsFile()).thenReturn(projectDir); Mockito.when(task.getProjectDir()).thenReturn(projectDirProperty); - File input = Paths.get("unitTests", "projectDir", "someInput").toFile(); + File input = Path.of("unitTests", "projectDir", "someInput").toFile(); Formatter formatter = Mockito.mock(Formatter.class); Assertions.assertThatThrownBy(() -> task.processInputFile(null, formatter, input, "someInput")).hasMessageContaining(input.toString()); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/TargetExcludeIfContentContainsTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/TargetExcludeIfContentContainsTest.java index f1a2cf4298..5acfa305be 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/TargetExcludeIfContentContainsTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/TargetExcludeIfContentContainsTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2023 DiffPlug + * Copyright 2020-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,10 +31,11 @@ void targetExcludeIfContentContainsWithOneValue() throws IOException { " custom 'lowercase', { str -> str.toLowerCase() }", " }", "}"); - String content = "// Generated by Mr. Roboto, do not edit.\n" + - "A B C\n" + - "D E F\n" + - "G H I"; + String content = """ + // Generated by Mr. Roboto, do not edit. + A B C + D E F + G H I"""; setFile("test_generated.md").toContent(content); setFile("test_manual.md").toLines( "A B C", @@ -62,14 +63,18 @@ void targetExcludeIfContentContainsWithMultipleSteps() throws IOException { " licenseHeader('" + "// My CopyRights header" + "', '--')", " }", "}"); - String generatedContent = "// Generated by Mr. Roboto, do not edit.\n" + - "--\n" + - "public final class MyMessage {}\n"; + String generatedContent = """ + // Generated by Mr. Roboto, do not edit. + -- + public final class MyMessage {} + """; setFile("test_generated.md").toContent(generatedContent); - String manualContent = "// Typo in License\n" + - "--\n" + - "public final class MyMessage {\n" + - "}"; + String manualContent = """ + // Typo in License + -- + public final class MyMessage { + }\ + """; setFile("test_manual.md").toContent(manualContent); gradleRunner().withArguments("spotlessApply").build(); @@ -77,10 +82,12 @@ void targetExcludeIfContentContainsWithMultipleSteps() throws IOException { assertFile("test_generated.md").hasContent(generatedContent); // `test_manual` does not, it changed. assertFile("test_manual.md").hasContent( - "// My CopyRights header\n" + - "--\n" + - "public final class mymessage {\n" + - "}"); + """ + // My CopyRights header + -- + public final class mymessage { + }\ + """); } @Test @@ -94,26 +101,30 @@ void targetExcludeIfContentContainsRegex() throws IOException { " custom 'lowercase', { str -> str.toLowerCase() }", " }", "}"); - String robotoContent = "A B C\n" + - "// Generated by Mr. Roboto, do not edit.\n" + - "D E F\n" + - "G H I"; + String robotoContent = """ + A B C + // Generated by Mr. Roboto, do not edit. + D E F + G H I"""; setFile("test_generated_roboto.md").toContent(robotoContent); - String callContent = "A B C\n" + - "D E F\n" + - "// Generated by Mrs. Call, do not edit.\n" + - "G H I"; + String callContent = """ + A B C + D E F + // Generated by Mrs. Call, do not edit. + G H I"""; setFile("test_generated_call.md").toContent(callContent); - String collaborationContent = "A B C\n" + - "// Generated by Mr. Roboto, do not edit.\n" + - "D E F\n" + - "// Generated by Mrs. Call, do not edit.\n" + - "G H I"; + String collaborationContent = """ + A B C + // Generated by Mr. Roboto, do not edit. + D E F + // Generated by Mrs. Call, do not edit. + G H I"""; setFile("test_generated_collaboration.md").toContent(collaborationContent); - String intruderContent = "A B C\n" + - "// Generated by K2000, do not edit.\n" + - "D E F\n" + - "G H I"; + String intruderContent = """ + A B C + // Generated by K2000, do not edit. + D E F + G H I"""; setFile("test_generated_intruder.md").toContent(intruderContent); setFile("test_manual.md").toLines( "A B C", @@ -128,10 +139,11 @@ void targetExcludeIfContentContainsRegex() throws IOException { assertFile("test_generated_collaboration.md").hasContent(collaborationContent); // Not part of the excluding values so has changed. assertFile("test_generated_intruder.md").hasContent( - "a b c\n" + - "// generated by k2000, do not edit.\n" + - "d e f\n" + - "g h i"); + """ + a b c + // generated by k2000, do not edit. + d e f + g h i"""); // `test_manual` does not, it changed. assertFile("test_manual.md").hasLines( "a b c", diff --git a/plugin-maven/build.gradle b/plugin-maven/build.gradle index c54783d56a..197ace7f2c 100644 --- a/plugin-maven/build.gradle +++ b/plugin-maven/build.gradle @@ -31,6 +31,8 @@ dependencies { compileOnly "org.apache.maven:maven-core:${VER_MAVEN_API}" compileOnly "org.eclipse.aether:aether-api:${VER_ECLIPSE_AETHER}" + compileOnly "jakarta.annotation:jakarta.annotation-api:3.0.0" + implementation "com.diffplug.durian:durian-core:${VER_DURIAN}" implementation "com.diffplug.durian:durian-io:${VER_DURIAN}" implementation "com.diffplug.durian:durian-collect:${VER_DURIAN}" 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 1ddda39c65..480178eab2 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 @@ -253,7 +253,7 @@ protected AbstractSpotlessMojo() { @Override public final void execute() throws MojoExecutionException { if (shouldSkip()) { - getLog().info(String.format("Spotless %s skipped", goal)); + getLog().info("Spotless %s skipped".formatted(goal)); return; } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FileLocator.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FileLocator.java index 088c35a3d0..09938e8ee6 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FileLocator.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FileLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.net.URISyntaxException; import java.nio.file.FileSystemNotFoundException; import java.nio.file.Path; -import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; @@ -146,7 +145,7 @@ private static File findDataDir() { } private static File findUserHome() { - var home = Paths.get(System.getenv("user.home")); + var home = Path.of(System.getenv("user.home")); return home.resolve(".rome").toAbsolutePath().toFile(); } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/GitRatchetMaven.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/GitRatchetMaven.java index f68ac295f6..ab3ec8b958 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/GitRatchetMaven.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/GitRatchetMaven.java @@ -1,5 +1,5 @@ /* - * Copyright 2020 DiffPlug + * Copyright 2020-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ import java.io.File; import java.io.IOException; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; @@ -64,7 +63,7 @@ Iterable getDirtyFiles(File baseDir, String ratchetFrom) throws IOExcept indexDiff.diff(); String workTreePath = repository.getWorkTree().getPath(); - Path baseDirPath = Paths.get(baseDir.getPath()); + Path baseDirPath = Path.of(baseDir.getPath()); Set dirtyPaths = new HashSet<>(indexDiff.getChanged()); dirtyPaths.addAll(indexDiff.getAdded()); @@ -93,7 +92,7 @@ Iterable getDirtyFiles(File baseDir, String ratchetFrom) throws IOExcept dirtyPaths.removeAll(indexDiff.getMissing()); return dirtyPaths.stream() - .map(path -> baseDirPath.relativize(Paths.get(workTreePath, path)).toString()) + .map(path -> baseDirPath.relativize(Path.of(workTreePath, path)).toString()) .collect(Collectors.toList()); } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java index 829b89a38a..f677979b6f 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java @@ -68,7 +68,7 @@ protected void process(String name, Iterable files, Formatter formatter, U boolean hasUnsuppressedLints = lintState.isHasLints(); if (hasDirtyState) { - getLog().info(String.format("clean file: %s", file)); + getLog().info("clean file: %s".formatted(file)); lintState.getDirtyState().writeCanonicalTo(file); buildContext.refresh(file); counter.cleaned(); @@ -105,10 +105,10 @@ protected void process(String name, Iterable files, Formatter formatter, U // We print the number of considered files which is useful when ratchetFrom is setup if (counter.getTotal() > 0) { - getLog().info(String.format("Spotless.%s is keeping %s files clean - %s were changed to be clean, %s were already clean, %s were skipped because caching determined they were already clean", + getLog().info("Spotless.%s is keeping %s files clean - %s were changed to be clean, %s were already clean, %s were skipped because caching determined they were already clean".formatted( name, counter.getTotal(), counter.getCleaned(), counter.getCheckedButAlreadyClean(), counter.getSkippedAsCleanCache())); } else { - getLog().debug(String.format("Spotless.%s has no target files. Examine your ``: https://github.com/diffplug/spotless/tree/main/plugin-maven#quickstart", name)); + getLog().debug("Spotless.%s has no target files. Examine your ``: https://github.com/diffplug/spotless/tree/main/plugin-maven#quickstart".formatted(name)); } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessCheckMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessCheckMojo.java index 2c318b9a95..910a004dfe 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessCheckMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessCheckMojo.java @@ -105,10 +105,10 @@ protected void process(String name, Iterable files, Formatter formatter, U // We print the number of considered files which is useful when ratchetFrom is setup if (counter.getTotal() > 0) { - getLog().info(String.format("Spotless.%s is keeping %s files clean - %s needs changes to be clean, %s were already clean, %s were skipped because caching determined they were already clean", + getLog().info("Spotless.%s is keeping %s files clean - %s needs changes to be clean, %s were already clean, %s were skipped because caching determined they were already clean".formatted( name, counter.getTotal(), counter.getCleaned(), counter.getCheckedButAlreadyClean(), counter.getSkippedAsCleanCache())); } else { - getLog().debug(String.format("Spotless.%s has no target files. Examine your ``: https://github.com/diffplug/spotless/tree/main/plugin-maven#quickstart", name)); + getLog().debug("Spotless.%s has no target files. Examine your ``: https://github.com/diffplug/spotless/tree/main/plugin-maven#quickstart".formatted(name)); } if (!problemFiles.isEmpty()) { @@ -124,7 +124,7 @@ protected void process(String name, Iterable files, Formatter formatter, U File file = firstLintProblem.getKey(); LintState lintState = firstLintProblem.getValue(); String stepName = lintState.getLintsByStep(formatter).keySet().iterator().next(); - throw new MojoExecutionException(String.format("Unable to format file %s%nStep '%s' found problem in '%s':%n%s", + throw new MojoExecutionException("Unable to format file %s%nStep '%s' found problem in '%s':%n%s".formatted( file, stepName, file.getName(), lintState.asStringOneLine(file, formatter))); } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessInstallPrePushHookMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessInstallPrePushHookMojo.java index 81a9f0403a..51fcb1d7cc 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessInstallPrePushHookMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessInstallPrePushHookMojo.java @@ -60,17 +60,17 @@ public void execute() throws MojoExecutionException, MojoFailureException { final var logger = new GitPreHookLogger() { @Override public void info(String format, Object... arguments) { - getLog().info(String.format(format, arguments)); + getLog().info(format.formatted(arguments)); } @Override public void warn(String format, Object... arguments) { - getLog().warn(String.format(format, arguments)); + getLog().warn(format.formatted(arguments)); } @Override public void error(String format, Object... arguments) { - getLog().error(String.format(format, arguments)); + getLog().error(format.formatted(arguments)); } }; diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/AbstractBiome.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/AbstractBiome.java index 3d1cf82ca4..3bf46f9be8 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/AbstractBiome.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/AbstractBiome.java @@ -15,7 +15,7 @@ */ package com.diffplug.spotless.maven.generic; -import java.nio.file.Paths; +import java.nio.file.Path; import org.apache.maven.plugins.annotations.Parameter; @@ -163,7 +163,7 @@ private String resolveConfigFile(FormatterStepConfig config) { * @return The resolved path to the Biome executable. */ private String resolveExePath(FormatterStepConfig config) { - var path = Paths.get(pathToExe); + var path = Path.of(pathToExe); if (path.getNameCount() == 1) { return path.toString(); } else { diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Prettier.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Prettier.java index c6b3e46e3c..36efe4e7ab 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Prettier.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Prettier.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,12 @@ package com.diffplug.spotless.maven.generic; import java.io.File; -import java.util.*; +import java.util.AbstractMap; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; import java.util.stream.Collectors; import org.apache.maven.plugins.annotations.Parameter; diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java index c719419923..8081a0d029 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2023 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,19 +28,18 @@ import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; -import java.nio.file.Paths; import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; -import javax.annotation.Nullable; - import org.apache.maven.plugin.logging.Log; import com.diffplug.common.annotations.VisibleForTesting; +import jakarta.annotation.Nullable; + class FileIndex { private static final String SEPARATOR = " "; @@ -102,8 +101,7 @@ static void delete(FileIndexConfig config, Log log) { } } - @Nullable - Instant getLastModifiedTime(Path file) { + @Nullable Instant getLastModifiedTime(Path file) { if (!file.startsWith(projectDir)) { return null; } @@ -169,7 +167,7 @@ private static Content readIndexContent(BufferedReader reader, Path projectDir, throw new IOException("Incorrect index file. No separator found in '" + line + "'"); } - Path relativeFile = Paths.get(line.substring(0, separatorIndex)); + Path relativeFile = Path.of(line.substring(0, separatorIndex)); Path absoluteFile = projectDir.resolve(relativeFile); if (Files.notExists(absoluteFile)) { log.info("File stored in the index does not exist: " + relativeFile); diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecking.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecking.java index f044b847c9..b02da5bf1b 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecking.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecking.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2023 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,10 +18,10 @@ import java.io.File; import java.nio.file.Path; -import javax.annotation.Nullable; - import org.apache.maven.plugins.annotations.Parameter; +import jakarta.annotation.Nullable; + public class UpToDateChecking { @Parameter @@ -34,8 +34,7 @@ public boolean isEnabled() { return enabled; } - @Nullable - public Path getIndexFile() { + @Nullable public Path getIndexFile() { return indexFile == null ? null : new File(indexFile).toPath(); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java index b0645c151e..fbf920b853 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package com.diffplug.spotless.maven.npm; import java.io.File; -import java.nio.file.Paths; +import java.nio.file.Path; import java.util.AbstractMap; import java.util.Arrays; import java.util.Collections; @@ -74,7 +74,7 @@ protected File cacheDir(FormatterStepConfig stepConfig) { if ("true".equals(this.npmInstallCache.toLowerCase(Locale.ROOT))) { return new File(buildDir(stepConfig), SPOTLESS_NPM_INSTALL_CACHE_DEFAULT_NAME); } - return Paths.get(this.npmInstallCache).toFile(); + return Path.of(this.npmInstallCache).toFile(); } protected File baseDir(FormatterStepConfig stepConfig) { diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/FileLocatorTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/FileLocatorTest.java index 9a80d07f1a..1e28359a3b 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/FileLocatorTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/FileLocatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import static org.mockito.Mockito.when; import java.io.File; -import java.nio.file.Paths; +import java.nio.file.Path; import org.codehaus.plexus.resource.ResourceManager; import org.junit.jupiter.api.BeforeEach; @@ -56,12 +56,12 @@ void locateNull() { @Test void locateXmlFile() throws Exception { - testFileLocator(Paths.get("tmp", "configs", "my-config.xml").toString(), "xml"); + testFileLocator(Path.of("tmp", "configs", "my-config.xml").toString(), "xml"); } @Test void locatePropertiesFile() throws Exception { - testFileLocator(Paths.get("home", "ubuntu", "my-other-config.properties").toString(), "properties"); + testFileLocator(Path.of("home", "ubuntu", "my-other-config.properties").toString(), "properties"); } @Test diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/IdeHookTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/IdeHookTest.java index 3c9a1a17d6..68820b2356 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/IdeHookTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/IdeHookTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,15 +30,16 @@ class IdeHookTest extends MavenIntegrationHarness { @BeforeEach void before() throws IOException { - writePomWithFormatSteps("\n" + - " DIRTY.md\n" + - " CLEAN.md\n" + - " \n" + - " \n" + - " Greetings to Mars\n" + - " World\n" + - " Mars\n" + - " "); + writePomWithFormatSteps(""" + + DIRTY.md + CLEAN.md + + + Greetings to Mars + World + Mars + """); dirty = setFile("DIRTY.md").toContent("World"); clean = setFile("CLEAN.md").toContent("Mars"); 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 e63f75f561..4e7a977174 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 @@ -223,8 +223,8 @@ protected MavenRunner mavenRunner() throws IOException { .withProjectDir(rootFolder()) .withRunner(runner); System.getProperties().forEach((key, value) -> { - if (key instanceof String && ((String) key).startsWith("spotless") && value instanceof String) { - mavenRunner.withSystemProperty((String) key, (String) value); + if (key instanceof String string && string.startsWith("spotless") && value instanceof String string1) { + mavenRunner.withSystemProperty(string, string1); } }); return mavenRunner; diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java index 11d52abc92..06edf437fc 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java @@ -82,7 +82,7 @@ private Map calculateEnvironment() { if (!systemProperties.isEmpty()) { // add system properties as environment variables as MAVEN_OPTS or append if already there String sysProps = systemProperties.entrySet().stream() - .map(entry -> String.format("-D%s=%s", entry.getKey(), entry.getValue())) + .map(entry -> "-D%s=%s".formatted(entry.getKey(), entry.getValue())) .collect(Collectors.joining(" ")); String mavenOpts = Stream.of(env.getOrDefault("MAVEN_OPTS", ""), sysProps) .collect(Collectors.joining(" ")); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpecificFilesTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpecificFilesTest.java index 6ce11d179f..1486fefa95 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpecificFilesTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpecificFilesTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ import java.io.IOException; import java.nio.file.Path; -import java.nio.file.Paths; import org.junit.jupiter.api.Test; @@ -26,9 +25,9 @@ private String testFile(int number, boolean absolute) throws IOException { String rel = "src/main/java/test" + number + ".java"; Path path; if (absolute) { - path = Paths.get(rootFolder().getAbsolutePath(), rel); + path = Path.of(rootFolder().getAbsolutePath(), rel); } else { - path = Paths.get(rel); + path = Path.of(rel); } String result = path.toString(); if (!isOnWindows()) { diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexConfigTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexConfigTest.java index 4d167bc18f..864a874542 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexConfigTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexConfigTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2022 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ import java.io.File; import java.nio.file.Path; -import java.nio.file.Paths; import org.apache.maven.model.Build; import org.apache.maven.project.MavenProject; @@ -32,7 +31,7 @@ void returnsCorrectProjectDir() { MavenProject project = mavenProject(); FileIndexConfig config = new FileIndexConfig(project, getIndexFile(project), PluginFingerprint.from("foo")); - assertThat(config.getProjectDir()).isEqualTo(Paths.get("projectDir")); + assertThat(config.getProjectDir()).isEqualTo(Path.of("projectDir")); } @Test @@ -41,7 +40,7 @@ void returnsCorrectIndexFile() { FileIndexConfig config = new FileIndexConfig(project, getIndexFile(project), PluginFingerprint.from("foo")); assertThat(config.getIndexFile()) - .isEqualTo(Paths.get("projectDir", "target", "spotless-index")); + .isEqualTo(Path.of("projectDir", "target", "spotless-index")); } @Test diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexTest.java index 8cd5e8a2f7..c5dcb70383 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2023 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.attribute.FileTime; import java.time.Instant; import java.util.List; @@ -214,7 +213,7 @@ void getLastModifiedTimeReturnsEmptyOptionalForUnknownFile() throws Exception { @Test void setLastModifiedTimeThrowsForNonProjectFile() { FileIndex index = FileIndex.read(config, log); - Path nonProjectFile = Paths.get("non-project-file"); + Path nonProjectFile = Path.of("non-project-file"); assertThatThrownBy(() -> index.setLastModifiedTime(nonProjectFile, Instant.now())).isInstanceOf(IllegalArgumentException.class); } @@ -256,7 +255,7 @@ void rewritesIndexFileThatReferencesNonExistingFile() throws Exception { @Test void writeFailsWhenIndexFilesDoesNotHaveParentDir() { - when(config.getIndexFile()).thenReturn(Paths.get("file-without-parent")); + when(config.getIndexFile()).thenReturn(Path.of("file-without-parent")); FileIndex index = FileIndex.read(config, log); assertThat(index.size()).isZero(); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtlintTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtlintTest.java index 2e4eaee791..b46a45a442 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtlintTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtlintTest.java @@ -34,12 +34,13 @@ void testKtlint() throws Exception { @Test void testKtlintEditorConfigOverride() throws Exception { - writePomWithKotlinSteps("\n" + - " \n" + - " true\n" + - " true\n" + - " \n" + - ""); + writePomWithKotlinSteps(""" + + + true + true + + """); String path = "src/main/kotlin/Main.kt"; setFile(path).toResource("kotlin/ktlint/experimentalEditorConfigOverride.dirty"); @@ -57,35 +58,38 @@ void testReadCodeStyleFromEditorConfigFile() throws Exception { @Test void testEditorConfigOverrideWithUnsetCodeStyleDoesNotOverrideEditorConfigCodeStyleWithDefault() throws Exception { setFile(".editorconfig").toResource("kotlin/ktlint/ktlint_official/.editorconfig"); - writePomWithKotlinSteps("\n" + - " \n" + - " true\n" + - " \n" + - ""); + writePomWithKotlinSteps(""" + + + true + + """); checkKtlintOfficialStyle(); } @Test void testSetEditorConfigCanOverrideEditorConfigFile() throws Exception { setFile(".editorconfig").toResource("kotlin/ktlint/intellij_idea/.editorconfig"); - writePomWithKotlinSteps("\n" + - " \n" + - " ktlint_official\n" + - " \n" + - ""); + writePomWithKotlinSteps(""" + + + ktlint_official + + """); checkKtlintOfficialStyle(); } @Test void testWithCustomRuleSetApply() throws Exception { - writePomWithKotlinSteps("\n" + - " \n" + - " io.nlopez.compose.rules:ktlint:0.4.25\n" + - " \n" + - " \n" + - " Composable\n" + - " \n" + - ""); + writePomWithKotlinSteps(""" + + + io.nlopez.compose.rules:ktlint:0.4.25 + + + Composable + + """); setFile("src/main/kotlin/Main.kt").toResource("kotlin/ktlint/listScreen.dirty"); ProcessRunner.Result result = mavenRunner().withArguments("spotless:check").runHasError(); Assertions.assertThat(result.toString()).contains("Composable functions that return Unit should start with an uppercase letter."); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmFrontendMavenPlugin.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmFrontendMavenPlugin.java index de030ab81c..95526614f4 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmFrontendMavenPlugin.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmFrontendMavenPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,31 +36,31 @@ private NpmFrontendMavenPlugin() { public static String[] pomPluginLines(String nodeVersion, String npmVersion) { return new String[]{ "", - String.format(" %s", GROUP_ID), - String.format(" %s", ARTIFACT_ID), - String.format(" %s", VERSION), + " %s".formatted(GROUP_ID), + " %s".formatted(ARTIFACT_ID), + " %s".formatted(VERSION), " ", " ", " install node and npm", " ", - String.format(" %s", GOAL_INSTALL_NODE_AND_NPM), + " %s".formatted(GOAL_INSTALL_NODE_AND_NPM), " ", " ", " ", " ", (nodeVersion != null ? " " + nodeVersion + "" : ""), (npmVersion != null ? " " + npmVersion + "" : ""), - String.format(" %s", INSTALL_DIRECTORY), + " %s".formatted(INSTALL_DIRECTORY), " ", "" }; } public static String installNpmMavenGoal() { - return String.format("%s:%s:%s", GROUP_ID, ARTIFACT_ID, GOAL_INSTALL_NODE_AND_NPM); + return "%s:%s:%s".formatted(GROUP_ID, ARTIFACT_ID, GOAL_INSTALL_NODE_AND_NPM); } public static String installedNpmPath() { - return String.format("%s/node/npm%s", INSTALL_DIRECTORY, System.getProperty("os.name").toLowerCase().contains("win") ? ".cmd" : ""); + return "%s/node/npm%s".formatted(INSTALL_DIRECTORY, System.getProperty("os.name").toLowerCase().contains("win") ? ".cmd" : ""); } } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmStepsWithNpmInstallCacheTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmStepsWithNpmInstallCacheTest.java index eabdd5c5fc..75d4b3f693 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmStepsWithNpmInstallCacheTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmStepsWithNpmInstallCacheTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; @@ -85,7 +84,7 @@ void prettierTypescriptWithDefaultCacheIsReusedOnSecondRun() throws Exception { .doesNotContain("Using cached node_modules for"); // recursively delete target folder to simulate a fresh run (except the default cache folder) - recursiveDelete(Paths.get(rootFolder().getAbsolutePath(), "target"), SPOTLESS_NPM_INSTALL_CACHE_DEFAULT_NAME); + recursiveDelete(Path.of(rootFolder().getAbsolutePath(), "target"), SPOTLESS_NPM_INSTALL_CACHE_DEFAULT_NAME); Result result2 = run("typescript", suffix); Assertions.assertThat(result2.stdOutUtf8()) @@ -129,7 +128,7 @@ void prettierTypescriptWithSpecificCacheIsUsedOnSecondRun() throws Exception { .doesNotContain("Using cached node_modules for"); // recursively delete target folder to simulate a fresh run - recursiveDelete(Paths.get(rootFolder().getAbsolutePath(), "target"), null); + recursiveDelete(Path.of(rootFolder().getAbsolutePath(), "target"), null); Result result2 = run("typescript", suffix); Assertions.assertThat(result2.stdOutUtf8()) diff --git a/settings.gradle b/settings.gradle index 8ab2d796e6..92bffc5031 100644 --- a/settings.gradle +++ b/settings.gradle @@ -23,6 +23,7 @@ plugins { id 'com.gradle.develocity' version '3.19.2' // https://github.com/equodev/equo-ide/blob/main/plugin-gradle/CHANGELOG.md id 'dev.equo.ide' version '1.7.8' apply false + id 'org.openrewrite.rewrite' version '7.16.0' apply false } dependencyResolutionManagement { diff --git a/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java b/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java index caf668ae8d..d81017aa36 100644 --- a/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java +++ b/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java @@ -87,9 +87,9 @@ public List listTestResources(String path) throws IOException { try (InputStream in = ResourceHarness.class.getResourceAsStream(path)) { if (in == null) { if (new File(path).isAbsolute()) { - throw new RuntimeException(String.format("Resource not found in classpath: '%s'", path)); + throw new RuntimeException("Resource not found in classpath: '%s'".formatted(path)); } else { - throw new RuntimeException(String.format("Resource not found in classpath: '%s' - did you mean '/%1$s'?", path)); + throw new RuntimeException("Resource not found in classpath: '%s' - did you mean '/%1$s'?".formatted(path)); } } try (BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) { diff --git a/testlib/src/main/java/com/diffplug/spotless/npm/EslintStyleGuide.java b/testlib/src/main/java/com/diffplug/spotless/npm/EslintStyleGuide.java index 874ae1905d..4e1d168a2a 100644 --- a/testlib/src/main/java/com/diffplug/spotless/npm/EslintStyleGuide.java +++ b/testlib/src/main/java/com/diffplug/spotless/npm/EslintStyleGuide.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -115,7 +115,7 @@ public String asGradleMapStringMergedWith(Map devDependencies) { public String asMavenXmlStringMergedWith(Map devDependencies) { return mergedWith(devDependencies).entrySet().stream() - .map(entry -> String.format("%s%s", entry.getKey(), entry.getValue())) + .map(entry -> "%s%s".formatted(entry.getKey(), entry.getValue())) .collect(Collectors.joining("", "", "")); } diff --git a/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java b/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java index d634119567..953dbb8884 100644 --- a/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,18 +31,20 @@ void cp1252asUtf8() throws UnsupportedEncodingException { cp1252asUtf8("", null); // single char cp1252asUtf8("a", null); - cp1252asUtf8("°", "Encoding error! Spotless uses UTF-8 by default. At line 1 col 1:\n" + - "� <- UTF-8\n" + - "° <- windows-1252\n" + - "° <- ISO-8859-1\n" + - "ー <- Shift_JIS"); + cp1252asUtf8("°", """ + Encoding error! Spotless uses UTF-8 by default. At line 1 col 1: + � <- UTF-8 + ° <- windows-1252 + ° <- ISO-8859-1 + ー <- Shift_JIS"""); // multiline cp1252asUtf8("\n123\nabc\n", null); - cp1252asUtf8("\n123\nabc°\nABC", "Encoding error! Spotless uses UTF-8 by default. At line 3 col 4:\n" + - "abc�␤AB <- UTF-8\n" + - "abc°␤AB <- windows-1252\n" + - "abc°␤AB <- ISO-8859-1\n" + - "abcー␤AB <- Shift_JIS"); + cp1252asUtf8("\n123\nabc°\nABC", """ + Encoding error! Spotless uses UTF-8 by default. At line 3 col 4: + abc�␤AB <- UTF-8 + abc°␤AB <- windows-1252 + abc°␤AB <- ISO-8859-1 + abcー␤AB <- Shift_JIS"""); } private void cp1252asUtf8(String test, @Nullable String expectedMessage) throws UnsupportedEncodingException { @@ -65,20 +67,22 @@ void utf8asCP1252() throws UnsupportedEncodingException { // multibyte UTF-8 can hide too utf8asCP1252("😂", null); // but some will trigger problems we can detect - utf8asCP1252("⍻", "Encoding error! You configured Spotless to use windows-1252. At line 1 col 2:\n" + - "â�» <- windows-1252\n" + - "⍻ <- UTF-8\n" + - "⍻ <- ISO-8859-1\n" + - "竝サ <- Shift_JIS"); // there are some codepoints where it doesn't + utf8asCP1252("⍻", """ + Encoding error! You configured Spotless to use windows-1252. At line 1 col 2: + â�» <- windows-1252 + ⍻ <- UTF-8 + ⍻ <- ISO-8859-1 + 竝サ <- Shift_JIS"""); // there are some codepoints where it doesn't // multiline utf8asCP1252("\n123\nabc\n", null); utf8asCP1252("\n123\nabc°\nABC", null); utf8asCP1252("\n123\nabc😂\nABC", null); - utf8asCP1252("\n123\nabc⍻\nABC", "Encoding error! You configured Spotless to use windows-1252. At line 3 col 5:\n" + - "bcâ�»␤A <- windows-1252\n" + - "bc⍻␤ABC <- UTF-8\n" + - "bc⍻␤A <- ISO-8859-1\n" + - "bc竝サ␤AB <- Shift_JIS"); + utf8asCP1252("\n123\nabc⍻\nABC", """ + Encoding error! You configured Spotless to use windows-1252. At line 3 col 5: + bcâ�»␤A <- windows-1252 + bc⍻␤ABC <- UTF-8 + bc⍻␤A <- ISO-8859-1 + bc竝サ␤AB <- Shift_JIS"""); } private void utf8asCP1252(String test, @Nullable String expectedMessage) throws UnsupportedEncodingException { diff --git a/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java b/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java index 6356e02660..027404901c 100644 --- a/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java @@ -209,7 +209,7 @@ public FormatterSettingsAssert containsSpecificValuesOf(File file) { for (String expectedValue : VALID_VALUES) { // A parsable (valid) file contains keys of the following format String validValueName = (null == expectedValue) ? "null" : expectedValue; - String key = String.format("%s.%s", fileName, validValueName); + String key = "%s.%s".formatted(fileName, validValueName); if (!settingsProps.containsKey(key)) { failWithMessage("Key <%s> not part of formatter settings.", key); } diff --git a/testlib/src/test/java/com/diffplug/spotless/GitPrePushHookInstallerTest.java b/testlib/src/test/java/com/diffplug/spotless/GitPrePushHookInstallerTest.java index b45ebfcde0..3c391b9a9b 100644 --- a/testlib/src/test/java/com/diffplug/spotless/GitPrePushHookInstallerTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/GitPrePushHookInstallerTest.java @@ -37,17 +37,17 @@ class GitPrePushHookInstallerTest extends ResourceHarness { private final GitPreHookLogger logger = new GitPreHookLogger() { @Override public void info(String format, Object... arguments) { - logs.add(String.format(format, arguments)); + logs.add(format.formatted(arguments)); } @Override public void warn(String format, Object... arguments) { - logs.add(String.format(format, arguments)); + logs.add(format.formatted(arguments)); } @Override public void error(String format, Object... arguments) { - logs.add(String.format(format, arguments)); + logs.add(format.formatted(arguments)); } }; diff --git a/testlib/src/test/java/com/diffplug/spotless/JvmTest.java b/testlib/src/test/java/com/diffplug/spotless/JvmTest.java index 801ca2ab24..9633e31bab 100644 --- a/testlib/src/test/java/com/diffplug/spotless/JvmTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/JvmTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,8 @@ void initialize() { void supportAdd() { Integer differentVersions[] = {0, 1, 2}; Arrays.asList(differentVersions).stream().forEach(v -> testSupport.add(v + Jvm.version(), v.toString())); - Arrays.asList(differentVersions).stream().forEach(v -> assertThat(testSupport.toString()).contains(String.format("Version %d", v))); - assertThat(testSupport.toString()).contains(String.format("%s alternatives", TEST_NAME)); + Arrays.asList(differentVersions).stream().forEach(v -> assertThat(testSupport.toString()).contains("Version %d".formatted(v))); + assertThat(testSupport.toString()).contains("%s alternatives".formatted(TEST_NAME)); } @ParameterizedTest(name = "{index} {1}") @@ -98,8 +98,8 @@ void supportListsMinimumJvmIfOnlyHigherJvmSupported() { testSupport.assertFormatterSupported(fmtVersion); }).getLints().get(0).getDetail(); assertThat(proposal).contains(String.format("on JVM %d", Jvm.version())); - assertThat(proposal).contains(String.format("%s %s requires JVM %d+", TEST_NAME, fmtVersion, higherJvmVersion)); - assertThat(proposal).contains(String.format("try %s alternatives", TEST_NAME)); + assertThat(proposal).contains("%s %s requires JVM %d+".formatted(TEST_NAME, fmtVersion, higherJvmVersion)); + assertThat(proposal).contains("try %s alternatives".formatted(TEST_NAME)); proposal = assertThrows(Exception.class, () -> { testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { @@ -107,22 +107,22 @@ void supportListsMinimumJvmIfOnlyHigherJvmSupported() { }).apply(""); }).getMessage(); assertThat(proposal).contains(String.format("on JVM %d", Jvm.version())); - assertThat(proposal).contains(String.format("%s %s requires JVM %d+", TEST_NAME, fmtVersion, higherJvmVersion)); - assertThat(proposal).contains(String.format("try %s alternatives", TEST_NAME)); + assertThat(proposal).contains("%s %s requires JVM %d+".formatted(TEST_NAME, fmtVersion, higherJvmVersion)); + assertThat(proposal).contains("try %s alternatives".formatted(TEST_NAME)); } for (String fmtVersion : Arrays.asList("1.2.4", "2", "1.2.5-SNAPSHOT")) { String proposal = assertThrows(Lint.ShortcutException.class, () -> { testSupport.assertFormatterSupported(fmtVersion); }).getLints().get(0).getDetail(); - assertThat(proposal).contains(String.format("%s %s requires JVM %d+", TEST_NAME, fmtVersion, higherJvmVersion + 1)); + assertThat(proposal).contains("%s %s requires JVM %d+".formatted(TEST_NAME, fmtVersion, higherJvmVersion + 1)); proposal = assertThrows(Exception.class, () -> { testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { throw testException; }).apply(""); }).getMessage(); - assertThat(proposal).contains(String.format("%s %s requires JVM %d+", TEST_NAME, fmtVersion, higherJvmVersion + 1)); + assertThat(proposal).contains("%s %s requires JVM %d+".formatted(TEST_NAME, fmtVersion, higherJvmVersion + 1)); } } @@ -159,9 +159,9 @@ void supportProposesJvmUpgrade() { }).apply(""); }).getMessage(); assertThat(proposal).contains(String.format("on JVM %d", Jvm.version())); - assertThat(proposal).contains(String.format("limits you to %s %s", TEST_NAME, "1")); - assertThat(proposal).contains(String.format("upgrade your JVM to %d+", higherJvm)); - assertThat(proposal).contains(String.format("then you can use %s %s", TEST_NAME, "2")); + assertThat(proposal).contains("limits you to %s %s".formatted(TEST_NAME, "1")); + assertThat(proposal).contains("upgrade your JVM to %d+".formatted(higherJvm)); + assertThat(proposal).contains("then you can use %s %s".formatted(TEST_NAME, "2")); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/biome/BiomeStepTest.java b/testlib/src/test/java/com/diffplug/spotless/biome/BiomeStepTest.java index 090c898df8..a47a5ad4cc 100644 --- a/testlib/src/test/java/com/diffplug/spotless/biome/BiomeStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/biome/BiomeStepTest.java @@ -20,7 +20,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Nested; @@ -40,7 +39,7 @@ class BiomeStepTest extends ResourceHarness { @BeforeAll static void createDownloadDir() throws IOException { // We do not want to download Biome each time we execute a test - var userHome = Paths.get(StandardSystemProperty.USER_HOME.value()); + var userHome = Path.of(StandardSystemProperty.USER_HOME.value()); downloadDir = userHome.resolve(".gradle").resolve("rome-dl-test").toAbsolutePath().normalize().toString(); } diff --git a/testlib/src/test/java/com/diffplug/spotless/cpp/CppDefaultsTest.java b/testlib/src/test/java/com/diffplug/spotless/cpp/CppDefaultsTest.java index b384298623..c7a3f104ea 100644 --- a/testlib/src/test/java/com/diffplug/spotless/cpp/CppDefaultsTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/cpp/CppDefaultsTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ void testDelimiterExpr() throws Exception { try { output = step.format(testSource, dummyFile); } catch (IllegalArgumentException e) { - throw new AssertionError(String.format("No delimiter found in '%s'", testSource), e); + throw new AssertionError("No delimiter found in '%s'".formatted(testSource), e); } String expected = testSource.replaceAll("(.*?)\\@", header + '\n'); assertThat(output).isEqualTo(expected).as("Unexpected header insertion for '$s'.", testSource); diff --git a/testlib/src/test/java/com/diffplug/spotless/generic/FenceStepTest.java b/testlib/src/test/java/com/diffplug/spotless/generic/FenceStepTest.java index cf9b9c2ea4..0081b39b42 100644 --- a/testlib/src/test/java/com/diffplug/spotless/generic/FenceStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/generic/FenceStepTest.java @@ -132,8 +132,7 @@ public String getName() { return uppercase ? "uppercase" : "lowercase"; } - @org.jetbrains.annotations.Nullable - @Override + @org.jetbrains.annotations.Nullable @Override public String format(String rawUnix, File file) throws Exception { return uppercase ? rawUnix.toUpperCase() : rawUnix.toLowerCase(); } @@ -150,7 +149,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - return obj instanceof ToCaseStep && getName().equals(((ToCaseStep) obj).getName()); + return obj instanceof ToCaseStep tcs && getName().equals(tcs.getName()); } } } diff --git a/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java b/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java index b5e08d2232..6bc131cbc3 100644 --- a/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -133,15 +133,16 @@ void should_skip_lines_matching_predefined_pattern() throws Throwable { } private String licenceWithAddress() { - return "Copyright © $YEAR FooBar Inc. All Rights Reserved.\n" + - " *\n" + - " * Use of this software is covered by inscrutable legal protection and\n" + - " * complex automation. Violaters of undisclosed terms must expect\n" + - " * unforeseen consequences.\n" + - " *\n" + - " * FooBar, Inc.\n" + - " * 9 Food Truck\n" + - " * Perry Derry, TX 55656 USA"; + return """ + Copyright © $YEAR FooBar Inc. All Rights Reserved. + * + * Use of this software is covered by inscrutable legal protection and + * complex automation. Violaters of undisclosed terms must expect + * unforeseen consequences. + * + * FooBar, Inc. + * 9 Food Truck + * Perry Derry, TX 55656 USA"""; } private String header(String contents) throws IOException { diff --git a/testlib/src/test/java/com/diffplug/spotless/gherkin/GherkinUtilsStepTest.java b/testlib/src/test/java/com/diffplug/spotless/gherkin/GherkinUtilsStepTest.java index 6bc478027b..05fdc019ad 100644 --- a/testlib/src/test/java/com/diffplug/spotless/gherkin/GherkinUtilsStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/gherkin/GherkinUtilsStepTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2023 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -117,8 +117,8 @@ protected FormatterStep create() { } private static void doWithResource(StepHarness stepHarness, String name) { - String before = String.format("gherkin/%sBefore.feature", name); - String after = String.format("gherkin/%sAfter.feature", name); + String before = "gherkin/%sBefore.feature".formatted(name); + String after = "gherkin/%sAfter.feature".formatted(name); stepHarness.testResource(before, after); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/json/JsonFormatterStepCommonTests.java b/testlib/src/test/java/com/diffplug/spotless/json/JsonFormatterStepCommonTests.java index fbdb6e9a4e..5f72ddb582 100644 --- a/testlib/src/test/java/com/diffplug/spotless/json/JsonFormatterStepCommonTests.java +++ b/testlib/src/test/java/com/diffplug/spotless/json/JsonFormatterStepCommonTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2022-2023 DiffPlug + * Copyright 2022-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,9 +17,14 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; +import org.apiguardian.api.API; import org.junit.jupiter.api.Test; -import com.diffplug.spotless.*; +import com.diffplug.spotless.FormatterStep; +import com.diffplug.spotless.Provisioner; +import com.diffplug.spotless.SerializableEqualityTester; +import com.diffplug.spotless.StepHarness; +import com.diffplug.spotless.TestProvisioner; public abstract class JsonFormatterStepCommonTests { @@ -96,8 +101,8 @@ protected StepHarness getStepHarness() { } protected void doWithResource(String name) { - String before = String.format("json/%sBefore.json", name); - String after = String.format("json/%sAfter.json", name); + String before = "json/%sBefore.json".formatted(name); + String after = "json/%sAfter.json".formatted(name); getStepHarness().testResource(before, after); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/json/JsonSimpleStepTest.java b/testlib/src/test/java/com/diffplug/spotless/json/JsonSimpleStepTest.java index 947cb30136..c35760089a 100644 --- a/testlib/src/test/java/com/diffplug/spotless/json/JsonSimpleStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/json/JsonSimpleStepTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -125,8 +125,8 @@ protected FormatterStep create() { } private static void doWithResource(StepHarness stepHarness, String name) { - String before = String.format("json/%sBefore.json", name); - String after = String.format("json/%sAfter.json", name); + String before = "json/%sBefore.json".formatted(name); + String after = "json/%sAfter.json".formatted(name); stepHarness.testResource(before, after); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/rdf/RdfFormatterTest.java b/testlib/src/test/java/com/diffplug/spotless/rdf/RdfFormatterTest.java index 6257f10cb2..59777a35e3 100644 --- a/testlib/src/test/java/com/diffplug/spotless/rdf/RdfFormatterTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/rdf/RdfFormatterTest.java @@ -103,7 +103,7 @@ private List getBeforeAfterTestResources(String beforeDir, String aft .stream().noneMatch(out -> out.getFileName().equals(in.getFileName()))) .collect(Collectors.toList()); if (!missingOutputs.isEmpty()) { - throw new IllegalStateException(String.format("'after' directory %s is missing files corresponding to these 'before' files: %s", beforeDir, missingOutputs)); + throw new IllegalStateException("'after' directory %s is missing files corresponding to these 'before' files: %s".formatted(beforeDir, missingOutputs)); } List missingInputs = outputs .stream() @@ -111,13 +111,13 @@ private List getBeforeAfterTestResources(String beforeDir, String aft .stream().noneMatch(in -> in.getFileName().equals(o.getFileName()))) .collect(Collectors.toList()); if (!missingInputs.isEmpty()) { - throw new IllegalStateException(String.format("'before' directory %s is missing files corresponding to these 'after' files: %s", afterDir, missingInputs)); + throw new IllegalStateException("'before' directory %s is missing files corresponding to these 'after' files: %s".formatted(afterDir, missingInputs)); } List arguments = new ArrayList<>(); for (Path input : inputs) { Optional output = outputs.stream().filter(o -> o.getFileName().equals(input.getFileName())).findFirst(); if (output.isEmpty()) { - throw new IllegalStateException(String.format("'after' directory %s is missing file %s corresponding to 'before' file %s", afterDir, input.getFileName(), input)); + throw new IllegalStateException("'after' directory %s is missing file %s corresponding to 'before' file %s".formatted(afterDir, input.getFileName(), input)); } arguments.add(Arguments.of(unixRelative(input), unixRelative(output.get()))); }