diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 341bc4c815..7aed0c2d01 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ concurrency: cancel-in-progress: true jobs: sanityCheck: - name: spotlessCheck assemble testClasses + name: QA (spotlessCheck, assemble testClasses, rewriteDryRun) runs-on: ubuntu-latest env: buildcacheuser: ${{ secrets.BUILDCACHE_USER }} @@ -33,6 +33,8 @@ jobs: run: ./gradlew spotlessCheck - name: assemble testClasses run: ./gradlew assemble testClasses + - name: rewriteDryRun + run: ./gradlew rewriteDryRun --build-cache --info build: needs: sanityCheck strategy: @@ -66,10 +68,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 38af879390..4367ae741f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -16,6 +16,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( * Adds support for worktrees (fixes [#1765](https://github.com/diffplug/spotless/issues/1765)) * Bump default `google-java-format` version to latest `1.24.0` -> `1.28.0`. ([#2345](https://github.com/diffplug/spotless/pull/2345)) * Bump default `ktlint` version to latest `1.5.0` -> `1.7.1`. ([#2555](https://github.com/diffplug/spotless/pull/2555)) +* PoC: Add `rewrite` support for `errorprone.refasterrules` ([#2576](https://github.com/diffplug/spotless/pull/2576)) ## [3.3.1] - 2025-07-21 ### Fixed diff --git a/build.gradle b/build.gradle index fafd6abe43..ad2c5082dd 100644 --- a/build.gradle +++ b/build.gradle @@ -1,29 +1,23 @@ apply plugin: 'dev.equo.ide' -equoIde { - branding().title('Spotless').icon(file('_images/spotless_logo.png')) - welcome().openUrl('https://github.com/diffplug/spotless/blob/main/CONTRIBUTING.md') - gradleBuildship().autoImport('.') -} -repositories { - mavenCentral() -} - -apply from: rootProject.file('gradle/java-publish.gradle') apply from: rootProject.file('gradle/changelog.gradle') +apply from: rootProject.file('gradle/java-publish.gradle') +apply from: rootProject.file('gradle/spotless-freshmark.gradle') + allprojects { apply from: rootProject.file('gradle/spotless.gradle') + apply from: rootProject.file('gradle/rewrite.gradle') +} + +equoIde { + branding().title('Spotless').icon(file('_images/spotless_logo.png')) + welcome().openUrl('https://github.com/diffplug/spotless/blob/main/CONTRIBUTING.md') + gradleBuildship().autoImport('.') } -apply from: rootProject.file('gradle/spotless-freshmark.gradle') -spotless { - groovyGradle { - target '*.gradle', 'gradle/*.gradle' - } - format 'dotfiles', { - target '.gitignore', '.gitattributes', '.editorconfig' - leadingTabsToSpaces(2) - trimTrailingWhitespace() - endWithNewline() - } +dependencies { + rewrite("org.openrewrite.recipe:rewrite-migrate-java:3.14.1") + rewrite("org.openrewrite.recipe:rewrite-rewrite:0.10.1") + rewrite("org.openrewrite.recipe:rewrite-static-analysis:2.14.0") + rewrite("org.openrewrite.recipe:rewrite-third-party:0.24.1") } diff --git a/gradle/rewrite.gradle b/gradle/rewrite.gradle new file mode 100644 index 0000000000..a7ebeadfd8 --- /dev/null +++ b/gradle/rewrite.gradle @@ -0,0 +1,49 @@ +apply plugin: 'org.openrewrite.rewrite' + +rewrite { + activeRecipe( + "org.openrewrite.gradle.GradleBestPractices", + "org.openrewrite.java.RemoveUnusedImports", + "org.openrewrite.java.format.RemoveTrailingWhitespace", + "org.openrewrite.java.recipes.JavaRecipeBestPractices", + "org.openrewrite.java.recipes.RecipeTestingBestPractices", + "org.openrewrite.staticanalysis.EmptyBlock", + "org.openrewrite.staticanalysis.EqualsAvoidsNull", + "org.openrewrite.staticanalysis.JavaApiBestPractices", + "org.openrewrite.staticanalysis.LowercasePackage", + "org.openrewrite.staticanalysis.MissingOverrideAnnotation", + "org.openrewrite.staticanalysis.ModifierOrder", + "org.openrewrite.staticanalysis.NoFinalizer", + "org.openrewrite.staticanalysis.RemoveCallsToSystemGc", + "org.openrewrite.staticanalysis.RemoveUnneededAssertion", + "org.openrewrite.staticanalysis.RemoveUnusedLocalVariables", + "org.openrewrite.staticanalysis.RemoveUnusedPrivateFields", + "org.openrewrite.staticanalysis.RemoveUnusedPrivateMethods", + "org.openrewrite.staticanalysis.StringLiteralEquality", + "org.openrewrite.staticanalysis.UnnecessaryParentheses", + "org.openrewrite.text.EndOfLineAtEndOfFile", + "tech.picnic.errorprone.refasterrules.BugCheckerRulesRecipes", + "tech.picnic.errorprone.refasterrules.CollectionRulesRecipes", + "tech.picnic.errorprone.refasterrules.FileRulesRecipes", + "tech.picnic.errorprone.refasterrules.NullRulesRecipes", + "tech.picnic.errorprone.refasterrules.StreamRulesRecipes", + "tech.picnic.errorprone.refasterrules.StringRulesRecipes", + "tech.picnic.errorprone.refasterrules.SuggestedFixRulesRecipes", + //"org.openrewrite.java.migrate.UpgradeToJava17", + //"org.openrewrite.staticanalysis.CodeCleanup", + //"org.openrewrite.staticanalysis.UnnecessaryThrows", + ) + // bugs + exclusions.add("**AJacksonFormatterFunc.java") + exclusions.add("**NpmPathResolver.java") + exclusions.add("**NpmTestsWithoutNpmInstallationTest_gradle_node_plugin_example_*.gradle") + exclusions.add("**gradle/changelog.gradle") + exclusions.add("**gradle/java-publish.gradle") + exclusions.add("**lib-extra/build.gradle") + exclusions.add("**lib/build.gradle") + exclusions.add("**package-info.java") + exclusions.add("**plugin-maven/build.gradle") + exclusions.add("**settings.gradle") + exportDatatables = true + failOnDryRunResults = true +} diff --git a/gradle/spotless.gradle b/gradle/spotless.gradle index 1a10f7239d..0a20a4859f 100644 --- a/gradle/spotless.gradle +++ b/gradle/spotless.gradle @@ -1,5 +1,16 @@ apply plugin: 'com.diffplug.spotless' + spotless { + groovyGradle { + target '*.gradle', 'gradle/*.gradle' + greclipse().configFile rootProject.files('gradle/spotless.eclipseformat.xml', 'gradle/spotless.groovyformat.prefs') + } + format 'dotfiles', { + target '.gitignore', '.gitattributes', '.editorconfig' + leadingTabsToSpaces(2) + trimTrailingWhitespace() + endWithNewline() + } def noInternalDepsClosure = { String text = it /* @@ -7,27 +18,21 @@ spotless { * https://github.com/gradle/gradle/issues/3191 */ String regex = "import org\\.gradle\\.api\\.internal\\.(?!plugins\\.DslObject)(?!project\\.ProjectInternal)" - if ((text.contains('import org.gradle.internal.') || text.find(regex)) && - !text.contains('def noInternalDepsClosure')) { + if ((text.contains('import org.gradle.internal.') || text.find(regex)) + && !text.contains('def noInternalDepsClosure')) { throw new AssertionError("Accidental internal import") } } - if (project != rootProject) { - // the rootProject doesn't have any java - java { - ratchetFrom 'origin/main' - bumpThisNumberIfACustomStepChanges(1) - licenseHeaderFile rootProject.file('gradle/spotless.license') - importOrderFile rootProject.file('gradle/spotless.importorder') - eclipse().configFile rootProject.file('gradle/spotless.eclipseformat.xml') - trimTrailingWhitespace() - removeUnusedImports() - formatAnnotations() - custom 'noInternalDeps', noInternalDepsClosure - } - } - groovyGradle { - target '*.gradle' - greclipse().configFile rootProject.files('gradle/spotless.eclipseformat.xml', 'gradle/spotless.groovyformat.prefs') + java { + target '*.gitignore' + ratchetFrom 'origin/main' + bumpThisNumberIfACustomStepChanges(1) + licenseHeaderFile rootProject.file('gradle/spotless.license') + importOrderFile rootProject.file('gradle/spotless.importorder') + eclipse().configFile rootProject.file('gradle/spotless.eclipseformat.xml') + trimTrailingWhitespace() + removeUnusedImports() + formatAnnotations() + custom 'noInternalDeps', noInternalDepsClosure } } diff --git a/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/DefaultJavaElementComparator.java b/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/DefaultJavaElementComparator.java index 78791e240b..8ca872ca50 100644 --- a/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/DefaultJavaElementComparator.java +++ b/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/DefaultJavaElementComparator.java @@ -368,8 +368,8 @@ private boolean isSortPreserved(BodyDeclaration bodyDeclaration) { } private int preserveRelativeOrder(BodyDeclaration bodyDeclaration1, BodyDeclaration bodyDeclaration2) { - int value1 = ((Integer) bodyDeclaration1.getProperty(CompilationUnitSorter.RELATIVE_ORDER)); - int value2 = ((Integer) bodyDeclaration2.getProperty(CompilationUnitSorter.RELATIVE_ORDER)); + int value1 = (Integer) bodyDeclaration1.getProperty(CompilationUnitSorter.RELATIVE_ORDER); + int value2 = (Integer) bodyDeclaration2.getProperty(CompilationUnitSorter.RELATIVE_ORDER); return value1 - value2; } diff --git a/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/JdtFlags.java b/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/JdtFlags.java index 819168013f..5e9c798338 100644 --- a/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/JdtFlags.java +++ b/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/JdtFlags.java @@ -48,7 +48,7 @@ && isInterfaceOrAnnotationMember(bodyDeclaration)) } private static boolean isPackageVisible(BodyDeclaration bodyDeclaration) { - return (!isPrivate(bodyDeclaration) && !isProtected(bodyDeclaration) && !isPublic(bodyDeclaration)); + return !isPrivate(bodyDeclaration) && !isProtected(bodyDeclaration) && !isPublic(bodyDeclaration); } private static boolean isPrivate(BodyDeclaration bodyDeclaration) { diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/EquoBasedStepBuilder.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/EquoBasedStepBuilder.java index 55b3474a03..1cb8184f64 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/EquoBasedStepBuilder.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/EquoBasedStepBuilder.java @@ -20,12 +20,7 @@ import java.io.File; import java.io.IOException; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Properties; +import java.util.*; import javax.annotation.Nullable; @@ -127,7 +122,7 @@ public FormatterStep build() { var roundtrippableState = new EquoStep(formatterVersion, settingProperties, settingXml, FileSignature.promise(settingsFiles), JarState.promise(() -> { P2QueryResult query; try { - if (null != cacheDirectory) { + if (cacheDirectory != null) { CacheLocations.override_p2data = cacheDirectory.toPath().resolve("dev/equo/p2-data").toFile(); } query = createModelWithMirrors().query(P2ClientCache.PREFER_OFFLINE, P2QueryCache.ALLOW); @@ -190,8 +185,8 @@ static class EquoStep implements Serializable { ImmutableMap stepProperties) { this.semanticVersion = semanticVersion; - this.settingProperties = Optional.ofNullable(settingProperties).orElse(new ArrayList<>()); - this.settingXml = Optional.ofNullable(settingXml).orElse(new ArrayList<>()); + this.settingProperties = Objects.requireNonNullElse(settingProperties, new ArrayList<>()); + this.settingXml = Objects.requireNonNullElse(settingXml, new ArrayList<>()); this.settingsPromise = settingsPromise; this.jarPromise = jarPromise; this.stepProperties = stepProperties; @@ -218,8 +213,8 @@ public static class State implements Serializable { public State(String semanticVersion, JarState jarState, List settingProperties, List settingXml, FileSignature settingsFiles, ImmutableMap stepProperties) { this.semanticVersion = semanticVersion; this.jarState = jarState; - this.settingProperties = Optional.ofNullable(settingProperties).orElse(new ArrayList<>()); - this.settingXml = Optional.ofNullable(settingXml).orElse(new ArrayList<>()); + this.settingProperties = Objects.requireNonNullElse(settingProperties, new ArrayList<>()); + this.settingXml = Objects.requireNonNullElse(settingXml, new ArrayList<>()); this.settingsFiles = settingsFiles; this.stepProperties = stepProperties; } diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java index 2695068e5b..9d6491f281 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java @@ -146,7 +146,7 @@ static class CachedEndings implements Serializable { private static final long serialVersionUID = -2534772773057900619L; /** this is transient, to simulate PathSensitive.RELATIVE */ - transient final String rootDir; + final transient String rootDir; /** the line ending used for most files */ final String defaultEnding; /** any exceptions to that default, in terms of relative path from rootDir */ @@ -154,7 +154,7 @@ static class CachedEndings implements Serializable { CachedEndings(File projectDir, Runtime runtime, Iterable toFormat) { String rootPath = FileSignature.pathNativeToUnix(projectDir.getAbsolutePath()); - rootDir = rootPath.equals("/") ? rootPath : rootPath + "/"; + rootDir = "/".equals(rootPath) ? rootPath : rootPath + "/"; defaultEnding = runtime.defaultEnding; for (File file : toFormat) { String ending = runtime.getEndingFor(file); diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitRatchet.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitRatchet.java index 037d4d847b..ffc56971bc 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitRatchet.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitRatchet.java @@ -132,9 +132,9 @@ private static boolean worktreeIsCleanCheckout(TreeWalk treeWalk) { return treeWalk.idEqual(TREE, WORKDIR); } - private final static int TREE = 0; - private final static int INDEX = 1; - private final static int WORKDIR = 2; + private static final int TREE = 0; + private static final int INDEX = 1; + private static final int WORKDIR = 2; Map gitRoots = new HashMap<>(); Table rootTreeShaCache = HashBasedTable.create(); 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..e24afc9e90 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,8 +69,8 @@ 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; - throw (null == exception) ? exceptionWrapper : exception; + Exception exception = throwable instanceof Exception ? (Exception) throwable : null; + throw exception == null ? 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..ade9d5ec20 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,8 +97,8 @@ 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; - throw (null == exception) ? exceptionWrapper : exception; + Exception exception = throwable instanceof Exception ? (Exception) throwable : null; + throw exception == null ? exceptionWrapper : exception; } }); } diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/integration/DiffMessageFormatter.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/integration/DiffMessageFormatter.java index a0d056bc0a..b8a3478a5b 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/integration/DiffMessageFormatter.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/integration/DiffMessageFormatter.java @@ -251,7 +251,7 @@ public static Map.Entry diff(Path rootDir, Formatter formatter, } private static Map.Entry diff(CleanProvider formatter, File file) throws IOException { - String raw = new String(Files.readAllBytes(file.toPath()), formatter.getEncoding()); + String raw = Files.readString(file.toPath(), formatter.getEncoding()); String rawUnix = LineEnding.toUnix(raw); String formatted = formatter.getFormatted(file, rawUnix); String formattedUnix = LineEnding.toUnix(formatted); 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..6394f1f8bd 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 @@ -67,8 +67,8 @@ 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; - throw (null == exception) ? exceptionWrapper : exception; + Exception exception = throwable instanceof Exception ? (Exception) throwable : null; + throw exception == null ? exceptionWrapper : exception; } }; } @@ -85,8 +85,8 @@ 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; - throw (null == exception) ? exceptionWrapper : exception; + Exception exception = throwable instanceof Exception ? (Exception) throwable : null; + throw exception == null ? exceptionWrapper : exception; } } }); diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepTest.java index 7bfddc8e1c..e76e9264c0 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepTest.java @@ -24,8 +24,8 @@ import com.diffplug.spotless.extra.eclipse.EquoResourceHarness; public class GrEclipseFormatterStepTest extends EquoResourceHarness { - private final static String INPUT = "class F{ def m(){} }"; - private final static String EXPECTED = "class F{\n\tdef m(){}\n}"; + private static final String INPUT = "class F{ def m(){} }"; + private static final String EXPECTED = "class F{\n\tdef m(){}\n}"; public GrEclipseFormatterStepTest() { super(GrEclipseFormatterStep.createBuilder(TestProvisioner.mavenCentral())); diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStepTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStepTest.java index e4a2b7cc0e..d0759d8000 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStepTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStepTest.java @@ -19,6 +19,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; +import java.nio.file.Files; import java.util.Properties; import java.util.function.Consumer; import java.util.stream.Stream; @@ -33,7 +34,7 @@ import com.diffplug.spotless.extra.eclipse.EclipseResourceHarness; public class EclipseWtpFormatterStepTest { - private final static Jvm.Support JVM_SUPPORT = Jvm. support("Oldest Version").add(8, "4.8.0"); + private static final Jvm.Support JVM_SUPPORT = Jvm. support("Oldest Version").add(8, "4.8.0"); private static class NestedTests extends EclipseResourceHarness { private final String unformatted, formatted; @@ -76,7 +77,7 @@ void multipleConfigurations() throws Exception { private File createPropertyFile(Consumer config) throws IOException { Properties configProps = new Properties(); config.accept(configProps); - File tempFile = File.createTempFile("EclipseWtpFormatterStepTest-", ".properties"); + File tempFile = Files.createTempFile("EclipseWtpFormatterStepTest-", ".properties").toFile(); OutputStream tempOut = new FileOutputStream(tempFile); configProps.store(tempOut, "test properties"); tempOut.flush(); diff --git a/lib/src/jackson/java/com/diffplug/spotless/glue/json/JacksonJsonFormatterFunc.java b/lib/src/jackson/java/com/diffplug/spotless/glue/json/JacksonJsonFormatterFunc.java index 71215eb4a3..e312cdfc83 100644 --- a/lib/src/jackson/java/com/diffplug/spotless/glue/json/JacksonJsonFormatterFunc.java +++ b/lib/src/jackson/java/com/diffplug/spotless/glue/json/JacksonJsonFormatterFunc.java @@ -53,6 +53,7 @@ protected Class inferType(String input) { * @return a {@link JsonFactory}. May be overridden to handle alternative formats. * @see jackson-dataformats-text */ + @Override protected JsonFactory makeJsonFactory() { JsonFactory jsonFactory = new JsonFactoryBuilder().build(); diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java b/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java index 499314ee3d..44d211f5ad 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java @@ -102,7 +102,7 @@ public static FormatterProperties fromXmlContent(final Iterable content) } catch (IOException | IllegalArgumentException exception) { String message = String.format("Failed to add preferences from XML:%n%s%n", contentElement); final String detailedMessage = exception.getMessage(); - if (null != detailedMessage) { + if (detailedMessage != null) { message += String.format(" %s", detailedMessage); } throw new IllegalArgumentException(message, exception); @@ -113,7 +113,7 @@ public static FormatterProperties fromXmlContent(final Iterable content) public static FormatterProperties merge(Properties... properties) { FormatterProperties merged = new FormatterProperties(); - List.of(properties).stream().forEach((source) -> merged.properties.putAll(source)); + List.of(properties).forEach(source -> merged.properties.putAll(source)); return merged; } @@ -138,7 +138,7 @@ private void add(final File settingsFile) throws IllegalArgumentException { } catch (IOException | IllegalArgumentException exception) { String message = String.format("Failed to add properties from '%s' to formatter settings.", settingsFile); String detailedMessage = exception.getMessage(); - if (null != detailedMessage) { + if (detailedMessage != null) { message += String.format(" %s", detailedMessage); } throw new IllegalArgumentException(message, exception); @@ -189,7 +189,7 @@ private Properties executeWithSupplier(Supplier isSupplier) throws try (InputStream input = isSupplier.get()) { rootNode = getRootNode(input); String nodeName = rootNode.getNodeName(); - if (null == nodeName) { + if (nodeName == null) { throw new IllegalArgumentException("XML document does not contain a root node."); } } @@ -277,7 +277,7 @@ protected Properties execute(InputStream file, Node rootNode) throws IOException NamedNodeMap attributes = setting.getAttributes(); Node id = attributes.getNamedItem("id"); Node value = attributes.getNamedItem("value"); - if (null == id) { + if (id == null) { throw new IllegalArgumentException("Node 'setting' does not possess an 'id' attribute."); } String idString = id.getNodeValue(); @@ -285,7 +285,7 @@ protected Properties execute(InputStream file, Node rootNode) throws IOException * A missing value is interpreted as an empty string, * similar to the Properties behavior */ - String valString = (null == value) ? "" : value.getNodeValue(); + String valString = value == null ? "" : value.getNodeValue(); properties.setProperty(idString, valString); } return properties; @@ -317,7 +317,7 @@ private List getChildren(final Node node, final String nodeName) { private static String getProfileName(Node profile) { Node nameAttribute = profile.getAttributes().getNamedItem("name"); - return (null == nameAttribute) ? "" : nameAttribute.getNodeValue(); + return nameAttribute == null ? "" : nameAttribute.getNodeValue(); } private final String rootNodeName; diff --git a/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstaller.java b/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstaller.java index 7a627a070c..af1f9d9e8f 100644 --- a/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstaller.java +++ b/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstaller.java @@ -128,7 +128,7 @@ public void install() throws Exception { * such as file reading or writing errors */ private void uninstall(File gitHookFile) throws Exception { - final var hook = Files.readString(gitHookFile.toPath(), UTF_8); + final var hook = Files.readString(gitHookFile.toPath()); final int hookStart = hook.indexOf(HOOK_HEADER); final int hookEnd = hook.indexOf(HOOK_FOOTER) + HOOK_FOOTER.length(); // hookEnd exclusive, so must be last symbol \n @@ -279,7 +279,7 @@ private boolean isGitInstalled() { * @throws Exception if an error occurs when reading the file. */ private boolean isGitHookInstalled(File gitHookFile) throws Exception { - final var hook = Files.readString(gitHookFile.toPath(), UTF_8); + final var hook = Files.readString(gitHookFile.toPath()); return hook.contains(HOOK_HEADER) && hook.contains(HOOK_FOOTER); } diff --git a/lib/src/main/java/com/diffplug/spotless/JarState.java b/lib/src/main/java/com/diffplug/spotless/JarState.java index 76dee4f438..1b993c75ee 100644 --- a/lib/src/main/java/com/diffplug/spotless/JarState.java +++ b/lib/src/main/java/com/diffplug/spotless/JarState.java @@ -128,7 +128,7 @@ private static JarState provisionWithTransitives(boolean withTransitives, Collec Objects.requireNonNull(provisioner, "provisioner"); Set jars = provisioner.provisionWithTransitives(withTransitives, mavenCoordinates); if (jars.isEmpty()) { - throw new NoSuchElementException("Resolved to an empty result: " + mavenCoordinates.stream().collect(Collectors.joining(", "))); + throw new NoSuchElementException("Resolved to an empty result: " + String.join(", ", mavenCoordinates)); } FileSignature fileSignature = FileSignature.signAsSet(jars); return new JarState(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..f3c1002c56 100644 --- a/lib/src/main/java/com/diffplug/spotless/Jvm.java +++ b/lib/src/main/java/com/diffplug/spotless/Jvm.java @@ -89,10 +89,10 @@ private Support(String formatterName, Comparator formatterVersionComp */ public Support add(int minimumJvmVersion, V maxFormatterVersion) { Objects.requireNonNull(maxFormatterVersion); - if (null != jvm2fmtMaxVersion.put(minimumJvmVersion, maxFormatterVersion)) { + if (jvm2fmtMaxVersion.put(minimumJvmVersion, maxFormatterVersion) != null) { throw new IllegalArgumentException(String.format("Added duplicate entry for JVM %d+.", minimumJvmVersion)); } - if (null != fmtMaxVersion2jvmVersion.put(maxFormatterVersion, minimumJvmVersion)) { + if (fmtMaxVersion2jvmVersion.put(maxFormatterVersion, minimumJvmVersion) != null) { throw new IllegalArgumentException(String.format("Added duplicate entry for formatter version %s.", maxFormatterVersion)); } verifyVersionRangesDoNotIntersect(jvm2fmtMaxVersion, minimumJvmVersion, maxFormatterVersion); @@ -101,7 +101,7 @@ public Support add(int minimumJvmVersion, V maxFormatterVersion) { public Support addMin(int minimumJvmVersion, V minFormatterVersion) { Objects.requireNonNull(minFormatterVersion); - if (null != jvm2fmtMinVersion.put(minimumJvmVersion, minFormatterVersion)) { + if (jvm2fmtMinVersion.put(minimumJvmVersion, minFormatterVersion) != null) { throw new IllegalArgumentException(String.format("Added duplicate entry for JVM %d+.", minimumJvmVersion)); } verifyVersionRangesDoNotIntersect(jvm2fmtMinVersion, minimumJvmVersion, minFormatterVersion); @@ -110,11 +110,11 @@ 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)) { + if ((lower != null) && (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())); } Map.Entry higher = jvm2fmtVersion.higherEntry(minimumJvmVersion); - if ((null != higher) && (fmtVersionComparator.compare(formatterVersion, higher.getValue()) >= 0)) { + if ((higher != null) && (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())); } } @@ -123,13 +123,13 @@ private void verifyVersionRangesDoNotIntersect(NavigableMap jvm2fmtV @Nullable public V getRecommendedFormatterVersion() { Integer configuredJvmVersionOrNull = jvm2fmtMaxVersion.floorKey(Jvm.version()); - return (null == configuredJvmVersionOrNull) ? null : jvm2fmtMaxVersion.get(configuredJvmVersionOrNull); + return configuredJvmVersionOrNull == null ? null : jvm2fmtMaxVersion.get(configuredJvmVersionOrNull); } @Nullable public V getMinimumRequiredFormatterVersion() { Integer configuredJvmVersionOrNull = jvm2fmtMinVersion.floorKey(Jvm.version()); - return (null == configuredJvmVersionOrNull) ? null : jvm2fmtMinVersion.get(configuredJvmVersionOrNull); + return configuredJvmVersionOrNull == null ? null : jvm2fmtMinVersion.get(configuredJvmVersionOrNull); } /** @@ -153,7 +153,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)) { + if ((minimumFormatterVersion != null) && (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); } // otherwise all is well @@ -164,11 +164,11 @@ private String buildUpgradeJvmMessage(V fmtVersion) { StringBuilder builder = new StringBuilder(); builder.append(String.format("You are running Spotless on JVM %d", Jvm.version())); V recommendedFmtVersionOrNull = getRecommendedFormatterVersion(); - if (null != recommendedFmtVersionOrNull) { + if (recommendedFmtVersionOrNull != null) { builder.append(String.format(", which limits you to %s %s.%n", fmtName, recommendedFmtVersionOrNull)); } else { Entry nextFmtVersionOrNull = fmtMaxVersion2jvmVersion.ceilingEntry(fmtVersion); - if (null != nextFmtVersionOrNull) { + if (nextFmtVersionOrNull != null) { builder.append(String.format(". %s %s requires JVM %d+", fmtName, fmtVersion, nextFmtVersionOrNull.getValue())); } builder.append(String.format(".%n")); @@ -178,10 +178,10 @@ private String buildUpgradeJvmMessage(V fmtVersion) { private int getRequiredJvmVersion(V fmtVersion) { Entry entry = fmtMaxVersion2jvmVersion.ceilingEntry(fmtVersion); - if (null == entry) { + if (entry == null) { entry = fmtMaxVersion2jvmVersion.lastEntry(); } - if (null != entry) { + if (entry != null) { V maxKnownFmtVersion = jvm2fmtMaxVersion.get(entry.getValue()); if (fmtVersionComparator.compare(fmtVersion, maxKnownFmtVersion) <= 0) { return entry.getValue(); @@ -229,20 +229,20 @@ private String buildUpgradeFormatterMessage(V fmtVersion) { // check if the formatter is not supported on this jvm V minimumFormatterVersion = getMinimumRequiredFormatterVersion(); V recommendedFmtVersionOrNull = getRecommendedFormatterVersion(); - if ((null != minimumFormatterVersion) && (fmtVersionComparator.compare(fmtVersion, minimumFormatterVersion) < 0)) { + if ((minimumFormatterVersion != null) && (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)); - if (null != recommendedFmtVersionOrNull) { + if (recommendedFmtVersionOrNull != null) { builder.append(String.format("%s %s is the recommended version, which may have fixed this problem.%n", fmtName, recommendedFmtVersionOrNull)); } // check if the formatter is outdated on this jvm - } else if (null != recommendedFmtVersionOrNull && (fmtVersionComparator.compare(fmtVersion, recommendedFmtVersionOrNull) < 0)) { + } else if (recommendedFmtVersionOrNull != null && (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))); } else { V higherFormatterVersionOrNull = fmtMaxVersion2jvmVersion.higherKey(fmtVersion); - if (null != higherFormatterVersionOrNull) { + if (higherFormatterVersionOrNull != null) { 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)); diff --git a/lib/src/main/java/com/diffplug/spotless/LintSuppression.java b/lib/src/main/java/com/diffplug/spotless/LintSuppression.java index d84107bd3a..529d71b96b 100644 --- a/lib/src/main/java/com/diffplug/spotless/LintSuppression.java +++ b/lib/src/main/java/com/diffplug/spotless/LintSuppression.java @@ -50,9 +50,9 @@ public void setShortCode(String shortCode) { } public boolean suppresses(String relativePath, FormatterStep formatterStep, Lint lint) { - if (path.equals(ALL) || path.equals(relativePath)) { - if (step.equals(ALL) || formatterStep.getName().equals(this.step)) { - if (shortCode.equals(ALL) || lint.getShortCode().equals(this.shortCode)) { + if (ALL.equals(path) || path.equals(relativePath)) { + if (ALL.equals(step) || formatterStep.getName().equals(this.step)) { + if (ALL.equals(shortCode) || lint.getShortCode().equals(this.shortCode)) { return true; } } @@ -61,7 +61,7 @@ public boolean suppresses(String relativePath, FormatterStep formatterStep, Lint } public void ensureDoesNotSuppressAll() { - boolean suppressAll = path.equals(ALL) && step.equals(ALL) && shortCode.equals(ALL); + boolean suppressAll = ALL.equals(path) && ALL.equals(step) && ALL.equals(shortCode); if (suppressAll) { throw new IllegalArgumentException("You must specify a specific `file`, `step`, or `shortCode`."); } diff --git a/lib/src/main/java/com/diffplug/spotless/MoreIterables.java b/lib/src/main/java/com/diffplug/spotless/MoreIterables.java index c3b0e5f286..902ce2e86e 100644 --- a/lib/src/main/java/com/diffplug/spotless/MoreIterables.java +++ b/lib/src/main/java/com/diffplug/spotless/MoreIterables.java @@ -31,7 +31,7 @@ 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) + List shallowCopy = input instanceof Collection ? new ArrayList<>(((Collection) input).size()) : new ArrayList<>(); input.forEach(shallowCopy::add); diff --git a/lib/src/main/java/com/diffplug/spotless/NoLambda.java b/lib/src/main/java/com/diffplug/spotless/NoLambda.java index d2ca6c1401..bae76ad0ae 100644 --- a/lib/src/main/java/com/diffplug/spotless/NoLambda.java +++ b/lib/src/main/java/com/diffplug/spotless/NoLambda.java @@ -43,7 +43,7 @@ public interface NoLambda extends Serializable { public byte[] toBytes(); /** An implementation of NoLambda in which equality is based on the serialized representation of itself. */ - public static abstract class EqualityBasedOnSerialization implements NoLambda { + public abstract static class EqualityBasedOnSerialization implements NoLambda { private static final long serialVersionUID = 1733798699224768949L; @Override diff --git a/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java b/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java index c6dd44ca7b..39d07b5888 100644 --- a/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java +++ b/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java @@ -202,7 +202,7 @@ public Result(@Nonnull List args, int exitCode, @Nonnull byte[] stdOut, this.args = args; this.exitCode = exitCode; this.stdOut = stdOut; - this.stdErr = (stdErr == null ? new byte[0] : stdErr); + this.stdErr = stdErr == null ? new byte[0] : stdErr; } public List args() { diff --git a/lib/src/main/java/com/diffplug/spotless/biome/Architecture.java b/lib/src/main/java/com/diffplug/spotless/biome/Architecture.java index 29511842e2..0f81b87e04 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/Architecture.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/Architecture.java @@ -40,22 +40,22 @@ public static Architecture guess() { var msg = "Unsupported architecture " + arch + "/" + version + ", specify the path to the Biome executable manually"; - if (arch.equals("ppc64le")) { + if ("ppc64le".equals(arch)) { throw new IllegalStateException(msg); } - if (arch.equals("s390x")) { + if ("s390x".equals(arch)) { throw new IllegalStateException(msg); } - if (arch.equals("ppc64")) { + if ("ppc64".equals(arch)) { throw new IllegalStateException(msg); } - if (arch.equals("ppc")) { + if ("ppc".equals(arch)) { throw new IllegalStateException(msg); } - if (arch.equals("aarch64")) { + if ("aarch64".equals(arch)) { return ARM64; } - if (arch.equals("arm")) { + if ("arm".equals(arch)) { if (version.contains("v7")) { throw new IllegalStateException(msg); } 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..610e026413 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java @@ -24,12 +24,12 @@ public final class BiomeSettings { private static final Logger logger = LoggerFactory.getLogger(BiomeSettings.class); - private final static String CONFIG_NAME = "biome.json"; - private final static String DEFAULT_VERSION = "1.2.0"; - private final static String DOWNLOAD_FILE_PATTERN = "biome-%s-%s-%s"; - private final static String SHORT_NAME = "biome"; - private final static String URL_PATTERN_1X = "https://github.com/biomejs/biome/releases/download/cli%%2Fv%s/biome-%s"; - private final static String URL_PATTERN_2X = "https://github.com/biomejs/biome/releases/download/%%40biomejs%%2Fbiome%%40%s/biome-%s"; + private static final String CONFIG_NAME = "biome.json"; + private static final String DEFAULT_VERSION = "1.2.0"; + private static final String DOWNLOAD_FILE_PATTERN = "biome-%s-%s-%s"; + private static final String SHORT_NAME = "biome"; + private static final String URL_PATTERN_1X = "https://github.com/biomejs/biome/releases/download/cli%%2Fv%s/biome-%s"; + private static final String URL_PATTERN_2X = "https://github.com/biomejs/biome/releases/download/%%40biomejs%%2Fbiome%%40%s/biome-%s"; private BiomeSettings() {} 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..6395c4784c 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/IdeaStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/IdeaStep.java @@ -214,7 +214,7 @@ private static boolean isMacOs() { private String format(IdeaStepFormatterCleanupResources ideaStepFormatterCleanupResources, String unix, File file) throws Exception { // since we cannot directly work with the file, we need to write the unix string to a temporary file - File tempFile = File.createTempFile("spotless", file.getName()); + File tempFile = Files.createTempFile("spotless", file.getName()).toFile(); try { Files.write(tempFile.toPath(), unix.getBytes(StandardCharsets.UTF_8)); List params = getParams(tempFile); @@ -225,7 +225,7 @@ private String format(IdeaStepFormatterCleanupResources ideaStepFormatterCleanup LOGGER.debug("command finished with exit code: {}", result.exitCode()); LOGGER.debug("command finished with stdout: {}", result.assertExitZero(StandardCharsets.UTF_8)); - return Files.readString(tempFile.toPath(), StandardCharsets.UTF_8); + return Files.readString(tempFile.toPath()); } finally { Files.delete(tempFile.toPath()); } 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..49edfbde61 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java @@ -432,7 +432,6 @@ private static final class State implements Serializable { // group 1 is the basename of the annotation. private static final String annoNoArgRegex = "@(?:[A-Za-z_][A-Za-z0-9_.]*\\.)?([A-Za-z_][A-Za-z0-9_]*)"; - private static final Pattern annoNoArgPattern = Pattern.compile(annoNoArgRegex); // 3 non-empty cases: () (".*") (.*) private static final String annoArgRegex = "(?:\\(\\)|\\(\"[^\"]*\"\\)|\\([^\")][^)]*\\))?"; // group 1 is the basename of the annotation. 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..f244d9c98e 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java +++ b/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java @@ -195,7 +195,7 @@ private List mergeMatchingItems() { } } // if there is \n on the end, remove it - if (!template.isEmpty() && template.get(template.size() - 1).equals(ImportSorter.N)) { + if (!template.isEmpty() && ImportSorter.N.equals(template.get(template.size() - 1))) { template.remove(template.size() - 1); } return template; @@ -209,7 +209,7 @@ private List getResult(List sortedImported, String lineFormat) { List strings = new ArrayList<>(); for (String s : sortedImported) { - if (s.equals(ImportSorter.N)) { + if (ImportSorter.N.equals(s)) { strings.add(s); } else { strings.add(String.format(lineFormat, s) + ImportSorter.N); @@ -256,7 +256,7 @@ private static int compareWithWildcare(String string1, String string2, boolean w if (!samePrefix) { return string1.compareTo(string2); } - return (string1IsWildcard == wildcardsLast) ? 1 : -1; + return string1IsWildcard == wildcardsLast ? 1 : -1; } private static class LexicographicalOrderingComparator implements Comparator, Serializable { 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..c5b744867d 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java @@ -102,7 +102,7 @@ static final class State implements Serializable { } FormatterFunc createFormat() throws Exception { - final File configFile = (config != null) ? config.getOnlyFile() : null; + final File configFile = config != null ? config.getOnlyFile() : null; Class formatterFunc = jar.getClassLoader().loadClass("com.diffplug.spotless.glue.diktat.DiktatFormatterFunc"); Constructor constructor = formatterFunc.getConstructor( String.class, 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 2120dc144a..1ee8401fc7 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java @@ -24,7 +24,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Objects; -import java.util.Optional; import javax.annotation.Nullable; @@ -79,9 +78,9 @@ public enum Style { ; // @formatter:on - final private String format; - final private String since; - final private @Nullable String until; + private final String format; + private final String since; + private final @Nullable String until; Style(String format, String since) { this.format = format; @@ -346,35 +345,35 @@ private Object getCustomFormattingOptions(Class formatterClass) throws Except if (options != null) { if (BadSemver.version(version) < BadSemver.version(0, 17)) { formattingOptions = formattingOptions.getClass().getConstructor(int.class, int.class, int.class).newInstance( - /* maxWidth = */ Optional.ofNullable(options.maxWidth).orElse((Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), - /* blockIndent = */ Optional.ofNullable(options.blockIndent).orElse((Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), - /* continuationIndent = */ Optional.ofNullable(options.continuationIndent).orElse((Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions))); + /* maxWidth = */ Objects.requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), + /* blockIndent = */ Objects.requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), + /* continuationIndent = */ Objects.requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions))); } else if (BadSemver.version(version) < BadSemver.version(0, 19)) { formattingOptions = formattingOptions.getClass().getConstructor(int.class, int.class, int.class, boolean.class, boolean.class).newInstance( - /* maxWidth = */ Optional.ofNullable(options.maxWidth).orElse((Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), - /* blockIndent = */ Optional.ofNullable(options.blockIndent).orElse((Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), - /* continuationIndent = */ Optional.ofNullable(options.continuationIndent).orElse((Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), - /* removeUnusedImports = */ Optional.ofNullable(options.removeUnusedImports).orElse((Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), + /* maxWidth = */ Objects.requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), + /* blockIndent = */ Objects.requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), + /* continuationIndent = */ Objects.requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), + /* removeUnusedImports = */ Objects.requireNonNullElse(options.removeUnusedImports, (Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), /* debuggingPrintOpsAfterFormatting = */ (Boolean) formattingOptionsClass.getMethod("getDebuggingPrintOpsAfterFormatting").invoke(formattingOptions)); } else if (BadSemver.version(version) < BadSemver.version(0, 47)) { Class styleClass = classLoader.loadClass(formattingOptionsClass.getName() + "$Style"); formattingOptions = formattingOptions.getClass().getConstructor(styleClass, int.class, int.class, int.class, boolean.class, boolean.class).newInstance( /* style = */ formattingOptionsClass.getMethod("getStyle").invoke(formattingOptions), - /* maxWidth = */ Optional.ofNullable(options.maxWidth).orElse((Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), - /* blockIndent = */ Optional.ofNullable(options.blockIndent).orElse((Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), - /* continuationIndent = */ Optional.ofNullable(options.continuationIndent).orElse((Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), - /* removeUnusedImports = */ Optional.ofNullable(options.removeUnusedImports).orElse((Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), + /* maxWidth = */ Objects.requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), + /* blockIndent = */ Objects.requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), + /* continuationIndent = */ Objects.requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), + /* removeUnusedImports = */ Objects.requireNonNullElse(options.removeUnusedImports, (Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), /* debuggingPrintOpsAfterFormatting = */ (Boolean) formattingOptionsClass.getMethod("getDebuggingPrintOpsAfterFormatting").invoke(formattingOptions)); } else { Class styleClass = classLoader.loadClass(formattingOptionsClass.getName() + "$Style"); formattingOptions = formattingOptions.getClass().getConstructor(styleClass, int.class, int.class, int.class, boolean.class, boolean.class, boolean.class).newInstance( /* style = */ formattingOptionsClass.getMethod("getStyle").invoke(formattingOptions), - /* maxWidth = */ Optional.ofNullable(options.maxWidth).orElse((Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), - /* blockIndent = */ Optional.ofNullable(options.blockIndent).orElse((Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), - /* continuationIndent = */ Optional.ofNullable(options.continuationIndent).orElse((Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), - /* removeUnusedImports = */ Optional.ofNullable(options.removeUnusedImports).orElse((Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), + /* maxWidth = */ Objects.requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), + /* blockIndent = */ Objects.requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), + /* continuationIndent = */ Objects.requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), + /* removeUnusedImports = */ Objects.requireNonNullElse(options.removeUnusedImports, (Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), /* debuggingPrintOpsAfterFormatting = */ (Boolean) formattingOptionsClass.getMethod("getDebuggingPrintOpsAfterFormatting").invoke(formattingOptions), - /* manageTrailingCommas */ Optional.ofNullable(options.manageTrailingCommas).orElse((Boolean) formattingOptionsClass.getMethod("getManageTrailingCommas").invoke(formattingOptions))); + /* manageTrailingCommas */ Objects.requireNonNullElse(options.manageTrailingCommas, (Boolean) formattingOptionsClass.getMethod("getManageTrailingCommas").invoke(formattingOptions))); } } 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..a4e994a12c 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java @@ -43,9 +43,7 @@ Optional tryFind() { return fileCandidateFinders .stream() .map(Supplier::get) - .filter(Optional::isPresent) - .map(Optional::get) - .findFirst(); + .filter(Optional::isPresent).findFirst().map(Optional::get); } static class Builder { 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..a153ba9343 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java @@ -96,7 +96,7 @@ public boolean isNodeModulesPrepared() { // check if it is NOT empty return ThrowingEx.get(() -> { try (Stream entries = Files.list(nodeModulesInstallDirPath)) { - return entries.findFirst().isPresent(); + return entries.findAny().isPresent(); } }); } 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..882a78658c 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java @@ -65,7 +65,7 @@ static class ParentOfNodeModulesDirResolver implements Function { @Override public File apply(File file) { - if (file != null && file.isDirectory() && file.getName().equalsIgnoreCase("node_modules")) { + if (file != null && file.isDirectory() && "node_modules".equalsIgnoreCase(file.getName())) { return file.getParentFile(); } return file; diff --git a/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java index 27a1002df5..77ee164d5e 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java @@ -137,7 +137,7 @@ private String assertFilepathInConfigOptions(File file) { return prettierConfigOptions; } // if the file has no name, we cannot use it - if (file.getName().trim().length() == 0) { + if (file.getName().trim().isEmpty()) { return prettierConfigOptions; } // if it is not there, we add it at the beginning of the Options 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..4d98e3587a 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/SimpleRestClient.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/SimpleRestClient.java @@ -93,7 +93,7 @@ private String readInputStream(InputStream inputStream) throws IOException { } } - static abstract class SimpleRestException extends RuntimeException { + abstract static class SimpleRestException extends RuntimeException { private static final long serialVersionUID = -8260821395756603787L; public SimpleRestException() {} 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..c547db6bac 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/StandardNpmProcessFactory.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/StandardNpmProcessFactory.java @@ -42,7 +42,7 @@ public NpmLongRunningProcess createNpmServeProcess(NodeServerLayout nodeServerLa return new NpmServe(nodeServerLayout.nodeModulesDir(), formatterStepLocations, nodeServerInstanceId); } - private static abstract class AbstractStandardNpmProcess { + private abstract static class AbstractStandardNpmProcess { protected final ProcessRunner processRunner = ProcessRunner.usingRingBuffersOfCapacity(100 * 1024); // 100kB protected final File workingDir; 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..dfcf52fe50 100644 --- a/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java @@ -100,13 +100,13 @@ public ReflectionHelper(RdfFormatterStep.State state) this.TurtleFormatFormattingStyleClass = classLoader.loadClass("de.atextor.turtle.formatter.FormattingStyle"); Class[] innerClasses = TurtleFormatFormattingStyleClass.getDeclaredClasses(); this.TurtleFormatFormattingStyleBuilderClass = Arrays.stream(innerClasses) - .filter(c -> c.getSimpleName().equals("FormattingStyleBuilder")).findFirst().get(); - this.TurtleFormatKnownPrefix = Arrays.stream(innerClasses).filter(c -> c.getSimpleName().equals("KnownPrefix")).findFirst().get(); + .filter(c -> "FormattingStyleBuilder".equals(c.getSimpleName())).findFirst().get(); + this.TurtleFormatKnownPrefix = Arrays.stream(innerClasses).filter(c -> "KnownPrefix".equals(c.getSimpleName())).findFirst().get(); this.getSubject = JenaStatementClass.getMethod("getSubject"); this.getPredicate = JenaStatementClass.getMethod("getPredicate"); this.getObject = JenaStatementClass.getMethod("getObject"); this.isAnon = JenaRDFNodeClass.getMethod("isAnon"); - this.getGraph = JenaModelClass.getMethod(("getGraph")); + this.getGraph = JenaModelClass.getMethod("getGraph"); this.JenaGraphClass = classLoader.loadClass("org.apache.jena.graph.Graph"); this.JenaTriple = classLoader.loadClass("org.apache.jena.graph.Triple"); this.graphFindTriple = JenaGraphClass.getMethod("find", JenaTriple); @@ -201,10 +201,10 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl long line = (long) args[1]; long col = (long) args[2]; String severity = method.getName(); - if (severity.equals("warning") && !state.getConfig().isFailOnWarning()) { + if ("warning".equals(severity) && !state.getConfig().isFailOnWarning()) { logger.warn("{}({},{}): {}", this.filePath, line, col, message); } else { - if (severity.equals("warning")) { + if ("warning".equals(severity)) { logger.error("Formatter fails because of a parser warning. To make the formatter succeed in" + "the presence of warnings, set the configuration parameter 'failOnWarning' to 'false' (default: 'true')"); } @@ -504,7 +504,7 @@ public SortedModelInvocationHandler(ReflectionHelper reflectionHelper, Object je @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - if (method.getName().equals("listSubjects") && method.getParameterCount() == 0) { + if ("listSubjects".equals(method.getName()) && method.getParameterCount() == 0) { Object resIterator = method.invoke(jenaModel); List resources = new ArrayList<>(); while (hasNext(resIterator)) { diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/DBeaverSQLFormatterConfiguration.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/DBeaverSQLFormatterConfiguration.java index 58a0119a7f..3736039e65 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/DBeaverSQLFormatterConfiguration.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/DBeaverSQLFormatterConfiguration.java @@ -65,7 +65,7 @@ public DBeaverSQLFormatterConfiguration(Properties properties) { } private String getIndentString(String indentType, int indentSize) { - char indentChar = indentType.equals("space") ? ' ' : '\t'; + char indentChar = "space".equals(indentType) ? ' ' : '\t'; StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < indentSize; i++) { stringBuilder.append(indentChar); diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/FormatterToken.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/FormatterToken.java index fd5e3994f9..6910303260 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/FormatterToken.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/FormatterToken.java @@ -63,6 +63,7 @@ public int getPos() { return fPos; } + @Override public String toString() { final StringBuilder buf = new StringBuilder(); buf.append(getClass().getName()); diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/KeywordCase.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/KeywordCase.java index 45a7083a80..c7774b3b15 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/KeywordCase.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/KeywordCase.java @@ -22,16 +22,19 @@ */ enum KeywordCase { UPPER { + @Override public String transform(String value) { return value.toUpperCase(Locale.ENGLISH); } }, LOWER { + @Override public String transform(String value) { return value.toLowerCase(Locale.ENGLISH); } }, ORIGINAL { + @Override public String transform(String value) { return value; } diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokenizedFormatter.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokenizedFormatter.java index 01f0fd759e..8145154bad 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokenizedFormatter.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokenizedFormatter.java @@ -124,8 +124,8 @@ private List format(final List argList) { String token2String = t2.getString().toUpperCase(Locale.ENGLISH); // Concatenate tokens if (t0.getType() == TokenType.KEYWORD && t1.getType() == TokenType.SPACE && t2.getType() == TokenType.KEYWORD) { - if (((tokenString.equals("ORDER") || tokenString.equals("GROUP") || tokenString.equals("CONNECT")) && token2String.equals("BY")) || - ((tokenString.equals("START")) && token2String.equals("WITH"))) { + if ((("ORDER".equals(tokenString) || "GROUP".equals(tokenString) || "CONNECT".equals(tokenString)) && "BY".equals(token2String)) || + (("START".equals(tokenString)) && "WITH".equals(token2String))) { t0.setString(t0.getString() + " " + t2.getString()); argList.remove(index + 1); argList.remove(index + 1); @@ -133,14 +133,14 @@ private List format(final List argList) { } // Oracle style joins - if (tokenString.equals("(") && t1.getString().equals("+") && token2String.equals(")")) { //$NON-NLS-2$ //$NON-NLS-3$ + if ("(".equals(tokenString) && "+".equals(t1.getString()) && ")".equals(token2String)) { //$NON-NLS-2$ //$NON-NLS-3$ t0.setString("(+)"); argList.remove(index + 1); argList.remove(index + 1); } // JDBI bind list - if (tokenString.equals("<") && t1.getType() == TokenType.NAME && token2String.equals(">")) { + if ("<".equals(tokenString) && t1.getType() == TokenType.NAME && ">".equals(token2String)) { t0.setString(t0.getString() + t1.getString() + t2.getString()); argList.remove(index + 1); argList.remove(index + 1); @@ -155,16 +155,16 @@ private List format(final List argList) { token = argList.get(index); String tokenString = token.getString().toUpperCase(Locale.ENGLISH); if (token.getType() == TokenType.SYMBOL) { - if (tokenString.equals("(")) { + if ("(".equals(tokenString)) { functionBracket.add(isFunction(prev.getString()) ? Boolean.TRUE : Boolean.FALSE); bracketIndent.add(indent); indent++; index += insertReturnAndIndent(argList, index + 1, indent); - } else if (tokenString.equals(")") && !bracketIndent.isEmpty() && !functionBracket.isEmpty()) { + } else if (")".equals(tokenString) && !bracketIndent.isEmpty() && !functionBracket.isEmpty()) { indent = bracketIndent.remove(bracketIndent.size() - 1); index += insertReturnAndIndent(argList, index, indent); functionBracket.remove(functionBracket.size() - 1); - } else if (tokenString.equals(",")) { + } else if (",".equals(tokenString)) { index += insertReturnAndIndent(argList, index + 1, indent); } else if (statementDelimiters.contains(tokenString)) { indent = 0; @@ -292,10 +292,10 @@ private List format(final List argList) { FormatterToken t3 = argList.get(index - 3); FormatterToken t4 = argList.get(index - 4); - if (t4.getString().equals("(") + if ("(".equals(t4.getString()) && t3.getString().trim().isEmpty() && t1.getString().trim().isEmpty() - && t0.getString().equalsIgnoreCase(")")) { + && ")".equalsIgnoreCase(t0.getString())) { t4.setString(t4.getString() + t2.getString() + t0.getString()); argList.remove(index); argList.remove(index - 1); @@ -311,11 +311,11 @@ private List format(final List argList) { if (prev.getType() != TokenType.SPACE && token.getType() != TokenType.SPACE && !token.getString().startsWith("(")) { - if (token.getString().equals(",") || statementDelimiters.contains(token.getString())) { + if (",".equals(token.getString()) || statementDelimiters.contains(token.getString())) { continue; } if (isFunction(prev.getString()) - && token.getString().equals("(")) { + && "(".equals(token.getString())) { continue; } if (token.getType() == TokenType.VALUE && prev.getType() == TokenType.NAME) { @@ -373,7 +373,7 @@ private boolean isJoinStart(List argList, int index) { if (token.getType() == TokenType.SPACE) { continue; } - if (token.getString().equals("JOIN")) { + if ("JOIN".equals(token.getString())) { return true; } if (!contains(JOIN_BEGIN, token.getString())) { diff --git a/lib/src/scalafmt/java/com/diffplug/spotless/glue/scalafmt/ScalafmtFormatterFunc.java b/lib/src/scalafmt/java/com/diffplug/spotless/glue/scalafmt/ScalafmtFormatterFunc.java index ab7e56ba45..f839656da4 100644 --- a/lib/src/scalafmt/java/com/diffplug/spotless/glue/scalafmt/ScalafmtFormatterFunc.java +++ b/lib/src/scalafmt/java/com/diffplug/spotless/glue/scalafmt/ScalafmtFormatterFunc.java @@ -43,7 +43,7 @@ public ScalafmtFormatterFunc(FileSignature configSignature) throws Exception { config = (ScalafmtConfig) method.invoke(ScalafmtConfig$.MODULE$); } else { File file = configSignature.getOnlyFile(); - String configStr = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + String configStr = Files.readString(file.toPath()); config = Scalafmt.parseHoconConfig(configStr).get(); } diff --git a/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java b/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java index f5abef6614..7d5c4b048e 100644 --- a/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java +++ b/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java @@ -41,7 +41,7 @@ public SortPomFormatterFunc(SortPomCfg cfg) { @Override public String apply(String input) throws Exception { // SortPom expects a file to sort, so we write the input into a temporary file - File pom = File.createTempFile("pom", ".xml"); + File pom = Files.createTempFile("pom", ".xml").toFile(); pom.deleteOnExit(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(pom, Charset.forName(cfg.encoding)))) { writer.write(input); 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..92603a91ad 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 @@ -62,7 +62,7 @@ private static String loadAndWriteText(Path path, String name) throws IOExceptio try (InputStream is = KtLintCompat0Dot48Dot0AdapterTest.class.getResourceAsStream("/" + name)) { Files.copy(is, path.resolve(name)); } - return new String(Files.readAllBytes(path.resolve(name)), StandardCharsets.UTF_8); + return Files.readString(path.resolve(name)); } } 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..f8f0dfa171 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 @@ -60,7 +60,7 @@ private static String loadAndWriteText(Path path, String name) throws IOExceptio try (InputStream is = KtLintCompat0Dot49Dot0AdapterTest.class.getResourceAsStream("/" + name)) { Files.copy(is, path.resolve(name)); } - return new String(Files.readAllBytes(path.resolve(name)), StandardCharsets.UTF_8); + return Files.readString(path.resolve(name)); } } 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..7874bb7c3e 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 @@ -60,7 +60,7 @@ private static String loadAndWriteText(Path path, String name) throws IOExceptio try (InputStream is = KtLintCompat0Dot50Dot0AdapterTest.class.getResourceAsStream("/" + name)) { Files.copy(is, path.resolve(name)); } - return new String(Files.readAllBytes(path.resolve(name)), StandardCharsets.UTF_8); + return Files.readString(path.resolve(name)); } } 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..c24e69ad4d 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 @@ -60,7 +60,7 @@ private static String loadAndWriteText(Path path, String name) throws IOExceptio try (InputStream is = KtLintCompat1Dot0Dot0AdapterTest.class.getResourceAsStream("/" + name)) { Files.copy(is, path.resolve(name)); } - return new String(Files.readAllBytes(path.resolve(name)), StandardCharsets.UTF_8); + return Files.readString(path.resolve(name)); } } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/CssExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/CssExtension.java index 2491faa04e..fa7af5a3b4 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/CssExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/CssExtension.java @@ -43,6 +43,7 @@ protected void setupTask(SpotlessTask task) { * offline, you can specify the path to the Biome executable via * {@code biome().pathToExe(...)}. */ + @Override public BiomeCss biome() { return biome(null); } @@ -54,6 +55,7 @@ public BiomeCss biome() { * {@code biome().pathToExe(...)}. * @param version Biome version to use. */ + @Override public BiomeCss biome(String version) { var biomeConfig = new BiomeCss(version); addStep(biomeConfig.createStep()); 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 09ba60fcaa..950ff1f41d 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 @@ -759,7 +759,7 @@ protected void replaceStep() { replaceStep.accept(createStep()); } - abstract protected FormatterStep createStep(); + protected abstract FormatterStep createStep(); } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/IdeHook.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/IdeHook.java index 8b7253fd8c..923c92a2cd 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/IdeHook.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/IdeHook.java @@ -47,9 +47,9 @@ static class State extends NoLambda.EqualityBasedOnSerialization { } } - final static String PROPERTY = "spotlessIdeHook"; - final static String USE_STD_IN = "spotlessIdeHookUseStdIn"; - final static String USE_STD_OUT = "spotlessIdeHookUseStdOut"; + static final String PROPERTY = "spotlessIdeHook"; + static final String USE_STD_IN = "spotlessIdeHookUseStdIn"; + static final String USE_STD_OUT = "spotlessIdeHookUseStdOut"; private static void dumpIsClean() { System.err.println("IS CLEAN"); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavascriptExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavascriptExtension.java index 043fd8237a..894d18017c 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavascriptExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavascriptExtension.java @@ -58,7 +58,7 @@ public JavascriptEslintConfig eslint(Map devDependencies) { return eslint; } - public static abstract class EslintBaseConfig> + public abstract static class EslintBaseConfig> extends NpmStepConfig> { Map devDependencies = new LinkedHashMap<>(); @@ -100,6 +100,7 @@ public JavascriptEslintConfig(Map devDependencies) { super(getProject(), JavascriptExtension.this::replaceStep, devDependencies); } + @Override public FormatterStep createStep() { final Project project = getProject(); @@ -140,11 +141,13 @@ public PrettierConfig prettier(Map devDependencies) { * offline, you can specify the path to the Biome executable via * {@code biome().pathToExe(...)}. */ + @Override public BiomeJs biome() { return biome(null); } /** Downloads the given Biome version from the network. */ + @Override public BiomeJs biome(String version) { var biomeConfig = new BiomeJs(version); addStep(biomeConfig.createStep()); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JsonExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JsonExtension.java index df0e5e6061..27ddeead22 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JsonExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JsonExtension.java @@ -63,11 +63,13 @@ public JacksonJsonGradleConfig jackson() { * offline, you can specify the path to the Biome executable via * {@code biome().pathToExe(...)}. */ + @Override public BiomeJson biome() { return biome(null); } /** Downloads the given Biome version from the network. */ + @Override public BiomeJson biome(String version) { var biomeConfig = new BiomeJson(version); addStep(biomeConfig.createStep()); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java index 175a828a66..5b2316fdf7 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java @@ -143,7 +143,7 @@ void init(SpotlessTaskImpl impl) { private String getTaskPathPrefix() { String path = getProjectPath().get(); - return path.equals(":") ? ":" : path + ":"; + return ":".equals(path) ? ":" : path + ":"; } private static String calculateGradleCommand() { 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 7241f018d0..f77cce45df 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 @@ -54,6 +54,7 @@ public abstract class SpotlessTaskImpl extends SpotlessTask { abstract Property getIdeHookState(); @Internal + @Override abstract DirectoryProperty getProjectDir(); void init(Provider service) { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskService.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskService.java index b58ff9005a..6d09ada714 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskService.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskService.java @@ -110,7 +110,7 @@ static void usesServiceTolerateTestFailure(DefaultTask task, Provider getSpotlessCleanDirectory(); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java index 1e7c9efc24..af9955aecb 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java @@ -112,6 +112,7 @@ private TypescriptFormatExtension configFile(TsConfigFileType filetype, Object p return this; } + @Override public FormatterStep createStep() { final Project project = getProject(); @@ -207,6 +208,7 @@ public TypescriptEslintConfig tsconfigFile(Object path) { return this; } + @Override public FormatterStep createStep() { final Project project = getProject(); @@ -228,11 +230,13 @@ protected EslintConfig eslintConfig() { * offline, you can specify the path to the Biome executable via * {@code biome().pathToExe(...)}. */ + @Override public BiomeTs biome() { return biome(null); } /** Downloads the given Biome version from the network. */ + @Override public BiomeTs biome(String version) { var biomeConfig = new BiomeTs(version); addStep(biomeConfig.createStep()); 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..f807940e5e 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 @@ -133,7 +133,7 @@ private AbstractStringAssert checkRanAgainstNoneButError() throws IOException private String taskRanAgainst(String task, String... ranAgainst) throws IOException { pauseForFilesystem(); String console = StringPrinter.buildString(Errors.rethrow().wrap(printer -> { - boolean expectFailure = task.equals("spotlessCheck") && !isClean(); + boolean expectFailure = "spotlessCheck".equals(task) && !isClean(); if (expectFailure) { gradleRunner().withArguments(task).forwardStdOutput(printer.toWriter()).forwardStdError(printer.toWriter()).buildAndFail(); } else { diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationHarness.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationHarness.java index 9e1738a02e..b334c7d8c8 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationHarness.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationHarness.java @@ -15,6 +15,7 @@ */ package com.diffplug.gradle.spotless; +import static com.diffplug.common.base.Strings.isNullOrEmpty; import static org.junit.jupiter.api.Assertions.fail; import java.io.File; @@ -231,7 +232,7 @@ static String buildResultToString(BuildResult result) { private static File getTestKitDir() { String gradleUserHome = System.getenv("GRADLE_USER_HOME"); - if (gradleUserHome == null || gradleUserHome.isEmpty()) { + if (isNullOrEmpty(gradleUserHome)) { gradleUserHome = new File(System.getProperty("user.home"), ".gradle").getAbsolutePath(); } return new File(gradleUserHome, "testkit"); 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 e5a8004f97..c8fb538b9a 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 @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.maven; +import static com.diffplug.common.base.Strings.isNullOrEmpty; import static java.util.stream.Collectors.toList; import java.io.File; @@ -290,7 +291,7 @@ private List collectFiles(FormatterFactory formatterFactory, FormatterConf } else { files = collectFilesFromFormatterFactory(formatterFactory); } - if (filePatterns == null || filePatterns.isEmpty()) { + if (isNullOrEmpty(filePatterns)) { return files; } final String[] includePatterns = this.filePatterns.split(","); @@ -396,8 +397,7 @@ private List getFormatterFactories() { } private List getFormatterStepFactories() { - return Stream.of(licenseHeader) - .filter(Objects::nonNull) + return Stream.ofNullable(licenseHeader) .collect(toList()); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ArtifactResolver.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ArtifactResolver.java index d0c8cb729a..293c4344b3 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ArtifactResolver.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ArtifactResolver.java @@ -41,7 +41,7 @@ public class ArtifactResolver { - private final static Exclusion EXCLUDE_ALL_TRANSITIVES = new Exclusion("*", "*", "*", "*"); + private static final Exclusion EXCLUDE_ALL_TRANSITIVES = new Exclusion("*", "*", "*", "*"); private final RepositorySystem repositorySystem; private final RepositorySystemSession session; 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 608dca0ef8..7fc60317eb 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 @@ -26,6 +26,8 @@ import com.diffplug.spotless.Formatter; import com.diffplug.spotless.maven.incremental.UpToDateChecker; +import static com.diffplug.common.base.Strings.isNullOrEmpty; + /** * Performs formatting of all source files according to configured formatters. */ @@ -86,6 +88,6 @@ protected void process(String name, Iterable files, Formatter formatter, U } private boolean isIdeHook() { - return !(spotlessIdeHook == null || spotlessIdeHook.isEmpty()); + return !isNullOrEmpty(spotlessIdeHook); } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/cpp/EclipseCdt.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/cpp/EclipseCdt.java index 92f4229ed3..f3dae7e3e3 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/cpp/EclipseCdt.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/cpp/EclipseCdt.java @@ -44,7 +44,7 @@ public class EclipseCdt implements FormatterStepFactory { public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) { EquoBasedStepBuilder eclipseConfig = EclipseCdtFormatterStep.createBuilder(stepConfig.getProvisioner()); eclipseConfig.setVersion(version == null ? EclipseCdtFormatterStep.defaultVersion() : version); - if (null != file) { + if (file != null) { File settingsFile = stepConfig.getFileLocator().locateFile(file); eclipseConfig.setPreferences(Arrays.asList(settingsFile)); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/EclipseWtp.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/EclipseWtp.java index e7e3d0e386..e978049f72 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/EclipseWtp.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/EclipseWtp.java @@ -40,7 +40,7 @@ public class EclipseWtp implements FormatterStepFactory { public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) { EclipseBasedStepBuilder eclipseConfig = type.createBuilder(stepConfig.getProvisioner()); eclipseConfig.setVersion(version == null ? EclipseWtpFormatterStep.defaultVersion() : version); - if (null != files) { + if (files != null) { eclipseConfig.setPreferences( stream(files).map(file -> stepConfig.getFileLocator().locateFile(file)).collect(toList())); } 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..f18e61296a 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 @@ -86,7 +86,7 @@ public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) { return new AbstractMap.SimpleEntry<>(entry.getKey(), Boolean.parseBoolean(entry.getValue())); } // Prettier v3 - plugins config will be a comma delimited list of plugins - if (entry.getKey().equals("plugins")) { + if ("plugins".equals(entry.getKey())) { List values = entry.getValue().isEmpty() ? List.of() : Arrays.asList(entry.getValue().split(",")); return new AbstractMap.SimpleEntry<>(entry.getKey(), values); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/groovy/GrEclipse.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/groovy/GrEclipse.java index 67ab40fbf2..266fff8598 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/groovy/GrEclipse.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/groovy/GrEclipse.java @@ -44,7 +44,7 @@ public class GrEclipse implements FormatterStepFactory { public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) { EquoBasedStepBuilder grEclipseConfig = GrEclipseFormatterStep.createBuilder(stepConfig.getProvisioner()); grEclipseConfig.setVersion(version == null ? GrEclipseFormatterStep.defaultVersion() : version); - if (null != file) { + if (file != null) { File settingsFile = stepConfig.getFileLocator().locateFile(file); grEclipseConfig.setPreferences(Arrays.asList(settingsFile)); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecker.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecker.java index 40dc84c8c6..b82d527320 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecker.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecker.java @@ -29,6 +29,7 @@ public interface UpToDateChecker extends AutoCloseable { void setUpToDate(Path file); + @Override void close(); static UpToDateChecker noop(MavenProject project, Path indexFile, Log log) { diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Eclipse.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Eclipse.java index 5e795ac93f..051ba10455 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Eclipse.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Eclipse.java @@ -61,35 +61,36 @@ public class Eclipse implements FormatterStepFactory { public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) { EclipseJdtFormatterStep.Builder eclipseConfig = EclipseJdtFormatterStep.createBuilder(stepConfig.getProvisioner()); eclipseConfig.setVersion(version == null ? EclipseJdtFormatterStep.defaultVersion() : version); - if (null != file) { + if (file != null) { File settingsFile = stepConfig.getFileLocator().locateFile(file); eclipseConfig.setPreferences(Arrays.asList(settingsFile)); } eclipseConfig.setP2Mirrors(p2Mirrors); - if (null != cacheDirectory) { + if (cacheDirectory != null) { eclipseConfig.setCacheDirectory(cacheDirectory); } - if (null != sortMembersEnabled) { + if (sortMembersEnabled != null) { eclipseConfig.sortMembersEnabled(sortMembersEnabled); } - if (null != sortMembersOrder) { + if (sortMembersOrder != null) { eclipseConfig.sortMembersOrder(sortMembersOrder); } - if (null != sortMembersDoNotSortFields) { + if (sortMembersDoNotSortFields != null) { eclipseConfig.sortMembersDoNotSortFields(sortMembersDoNotSortFields); } - if (null != sortMembersVisibilityOrder) { + if (sortMembersVisibilityOrder != null) { eclipseConfig.sortMembersVisibilityOrder(sortMembersVisibilityOrder); } - if (null != sortMembersVisibilityOrderEnabled) { + if (sortMembersVisibilityOrderEnabled != null) { eclipseConfig.sortMembersVisibilityOrderEnabled(sortMembersVisibilityOrderEnabled); } - if (null != cacheDirectory) { + if (cacheDirectory != null) { eclipseConfig.setCacheDirectory(cacheDirectory); } return eclipseConfig.build(); } + @Override public void init(RepositorySystemSession repositorySystemSession) { this.cacheDirectory = repositorySystemSession.getLocalRepository().getBasedir(); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/javascript/EslintJs.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/javascript/EslintJs.java index 483d38ae1e..f1b81a5d7d 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/javascript/EslintJs.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/javascript/EslintJs.java @@ -23,10 +23,12 @@ public class EslintJs extends AbstractEslint { + @Override protected EslintConfig eslintConfig(FormatterStepConfig stepConfig) { return new EslintConfig(this.configFile != null ? stepConfig.getFileLocator().locateFile(this.configFile) : null, this.configJs); } + @Override protected Map createDefaultDependencies() { return this.eslintVersion == null ? EslintFormatterStep.defaultDevDependencies() : EslintFormatterStep.defaultDevDependenciesWithEslint(this.eslintVersion); } diff --git a/plugin-maven/src/main/resources/META-INF/m2e/lifecycle-mapping-metadata.xml b/plugin-maven/src/main/resources/META-INF/m2e/lifecycle-mapping-metadata.xml index 9000b83704..3a77ae0f0b 100644 --- a/plugin-maven/src/main/resources/META-INF/m2e/lifecycle-mapping-metadata.xml +++ b/plugin-maven/src/main/resources/META-INF/m2e/lifecycle-mapping-metadata.xml @@ -29,4 +29,4 @@ - \ No newline at end of file + 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 f3e1f30355..77de2184c4 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 @@ -307,7 +307,7 @@ protected static Map buildPomXmlParams(String pluginVersion, Str private static String getSystemProperty(String name) { if (SPOTLESS_MAVEN_VERSION_IDE != null) { - if (name.equals("spotlessMavenPluginVersion")) { + if ("spotlessMavenPluginVersion".equals(name)) { return SPOTLESS_MAVEN_VERSION_IDE; } else { throw Unhandled.stringException(name); diff --git a/plugin-maven/src/test/resources/.mvn/wrapper/maven-wrapper.properties b/plugin-maven/src/test/resources/.mvn/wrapper/maven-wrapper.properties index c0b0297b0d..9e3a7db995 100755 --- a/plugin-maven/src/test/resources/.mvn/wrapper/maven-wrapper.properties +++ b/plugin-maven/src/test/resources/.mvn/wrapper/maven-wrapper.properties @@ -2,4 +2,4 @@ # maven-plugin-plugin 3.5 (see pom-build.xml.mustache). # The Maven version used for build and test is not relevant for compatibility. # Instead the versions of the provided dependencies (see pom-build.xml.mustache) must match. -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.2.5/apache-maven-3.2.5-bin.zip \ No newline at end of file +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.2.5/apache-maven-3.2.5-bin.zip diff --git a/settings.gradle b/settings.gradle index 53bfe6b161..4ca0471991 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.12.1' 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..088cca5a01 100644 --- a/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java +++ b/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java @@ -111,7 +111,7 @@ public String read(String path) throws IOException { } public String read(Path path, Charset encoding) throws IOException { - return new String(Files.readAllBytes(path), encoding); + return Files.readString(path, encoding); } public void replace(String path, String toReplace, String replaceWith) throws IOException { @@ -214,7 +214,7 @@ public void notSameAsResource(String resource) throws IOException { } public void matches(Consumer> conditions) throws IOException { - String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + String content = Files.readString(file.toPath()); conditions.accept(assertThat(content)); } } diff --git a/testlib/src/main/resources/biome/config/css-enabled.json b/testlib/src/main/resources/biome/config/css-enabled.json index 692de05fe6..3caae5f057 100644 --- a/testlib/src/main/resources/biome/config/css-enabled.json +++ b/testlib/src/main/resources/biome/config/css-enabled.json @@ -16,4 +16,4 @@ "linter": { "enabled": false } - } \ No newline at end of file + } diff --git a/testlib/src/main/resources/biome/config/line-width-120.json b/testlib/src/main/resources/biome/config/line-width-120.json index 8f14afa3f8..ca7e8ab588 100644 --- a/testlib/src/main/resources/biome/config/line-width-120.json +++ b/testlib/src/main/resources/biome/config/line-width-120.json @@ -8,4 +8,4 @@ "linter": { "enabled": false } - } \ No newline at end of file + } diff --git a/testlib/src/main/resources/biome/config/line-width-80.json b/testlib/src/main/resources/biome/config/line-width-80.json index 5ec998bd97..1a5f96934f 100644 --- a/testlib/src/main/resources/biome/config/line-width-80.json +++ b/testlib/src/main/resources/biome/config/line-width-80.json @@ -8,4 +8,4 @@ "linter": { "enabled": false } - } \ No newline at end of file + } diff --git a/testlib/src/main/resources/biome/css/fileBefore.css b/testlib/src/main/resources/biome/css/fileBefore.css index cfa88da947..c8d6a07b55 100644 --- a/testlib/src/main/resources/biome/css/fileBefore.css +++ b/testlib/src/main/resources/biome/css/fileBefore.css @@ -9,4 +9,4 @@ } - } \ No newline at end of file + } diff --git a/testlib/src/main/resources/biome/json/fileBefore.json b/testlib/src/main/resources/biome/json/fileBefore.json index 77182284c7..272184cce6 100644 --- a/testlib/src/main/resources/biome/json/fileBefore.json +++ b/testlib/src/main/resources/biome/json/fileBefore.json @@ -4,4 +4,4 @@ ], "b":9, "c" : null - } \ No newline at end of file + } diff --git a/testlib/src/main/resources/biome/json/package.json b/testlib/src/main/resources/biome/json/package.json index 94e8f88de5..b6b7f4f7a2 100644 --- a/testlib/src/main/resources/biome/json/package.json +++ b/testlib/src/main/resources/biome/json/package.json @@ -1,3 +1,3 @@ { "name": "test-package","version": "0.0.1" - } \ No newline at end of file + } diff --git a/testlib/src/main/resources/biome/json/packageAfter.json b/testlib/src/main/resources/biome/json/packageAfter.json index 94e8f88de5..b6b7f4f7a2 100644 --- a/testlib/src/main/resources/biome/json/packageAfter.json +++ b/testlib/src/main/resources/biome/json/packageAfter.json @@ -1,3 +1,3 @@ { "name": "test-package","version": "0.0.1" - } \ No newline at end of file + } diff --git a/testlib/src/main/resources/biome/json/packageBefore.json b/testlib/src/main/resources/biome/json/packageBefore.json index 94e8f88de5..b6b7f4f7a2 100644 --- a/testlib/src/main/resources/biome/json/packageBefore.json +++ b/testlib/src/main/resources/biome/json/packageBefore.json @@ -1,3 +1,3 @@ { "name": "test-package","version": "0.0.1" - } \ No newline at end of file + } diff --git a/testlib/src/main/resources/biome/ts/fileBefore.tsx b/testlib/src/main/resources/biome/ts/fileBefore.tsx index 38f24f8440..c48d341ea7 100644 --- a/testlib/src/main/resources/biome/ts/fileBefore.tsx +++ b/testlib/src/main/resources/biome/ts/fileBefore.tsx @@ -5,4 +5,4 @@ message:T, const Panel = ( cfg:Cfg):JSX.Element =>{ return (
{String(cfg.message)}
) ; - } \ No newline at end of file + } diff --git a/testlib/src/main/resources/clang/example.proto b/testlib/src/main/resources/clang/example.proto index a90d58bbd0..42d3a82853 100644 --- a/testlib/src/main/resources/clang/example.proto +++ b/testlib/src/main/resources/clang/example.proto @@ -2,4 +2,4 @@ message Testing { required string field1 = 1; required int32 field2 = 2; optional string field3 = 3; -} \ No newline at end of file +} diff --git a/testlib/src/main/resources/extra/config/preferences.properties b/testlib/src/main/resources/extra/config/preferences.properties index e20c058591..2d9c0ed889 100644 --- a/testlib/src/main/resources/extra/config/preferences.properties +++ b/testlib/src/main/resources/extra/config/preferences.properties @@ -1 +1 @@ -A=B \ No newline at end of file +A=B diff --git a/testlib/src/main/resources/formatter/properties/valid_line_oriented.properties b/testlib/src/main/resources/formatter/properties/valid_line_oriented.properties index b57ca9a66c..a71e120ad7 100644 --- a/testlib/src/main/resources/formatter/properties/valid_line_oriented.properties +++ b/testlib/src/main/resources/formatter/properties/valid_line_oriented.properties @@ -6,4 +6,4 @@ valid_line_oriented.properties.true=true valid_line_oriented.properties.42=42 valid_line_oriented.properties.null= common=valid_line_oriented.properties -#Final comment \ No newline at end of file +#Final comment diff --git a/testlib/src/main/resources/git_pre_hook/TestLicense.txt b/testlib/src/main/resources/git_pre_hook/TestLicense.txt index 2c4c9a3186..ee6010a3ca 100644 --- a/testlib/src/main/resources/git_pre_hook/TestLicense.txt +++ b/testlib/src/main/resources/git_pre_hook/TestLicense.txt @@ -1 +1 @@ -this is a test license! \ No newline at end of file +this is a test license! diff --git a/testlib/src/main/resources/java/idea/full.dirty.java b/testlib/src/main/resources/java/idea/full.dirty.java index 83923130e6..d1c0a48cd7 100644 --- a/testlib/src/main/resources/java/idea/full.dirty.java +++ b/testlib/src/main/resources/java/idea/full.dirty.java @@ -9,7 +9,7 @@ @ SpringBootApplication -public +public class Application{ diff --git a/testlib/src/main/resources/java/importsorter/import.properties b/testlib/src/main/resources/java/importsorter/import.properties index 24e9660a4e..dee6d52cc0 100644 --- a/testlib/src/main/resources/java/importsorter/import.properties +++ b/testlib/src/main/resources/java/importsorter/import.properties @@ -3,4 +3,4 @@ 3=\#com 2=org 1=javax -0=java \ No newline at end of file +0=java diff --git a/testlib/src/main/resources/java/importsorter/import_unmatched.properties b/testlib/src/main/resources/java/importsorter/import_unmatched.properties index 4d3fa4a4bb..cfc1613865 100644 --- a/testlib/src/main/resources/java/importsorter/import_unmatched.properties +++ b/testlib/src/main/resources/java/importsorter/import_unmatched.properties @@ -4,4 +4,4 @@ 3=java 2= 1=com.google -0=\# \ No newline at end of file +0=\# diff --git a/testlib/src/main/resources/json/emptyAfter.json b/testlib/src/main/resources/json/emptyAfter.json index e69de29bb2..8b13789179 100644 --- a/testlib/src/main/resources/json/emptyAfter.json +++ b/testlib/src/main/resources/json/emptyAfter.json @@ -0,0 +1 @@ + diff --git a/testlib/src/main/resources/json/emptyBefore.json b/testlib/src/main/resources/json/emptyBefore.json index e69de29bb2..8b13789179 100644 --- a/testlib/src/main/resources/json/emptyBefore.json +++ b/testlib/src/main/resources/json/emptyBefore.json @@ -0,0 +1 @@ + diff --git a/testlib/src/main/resources/json/invalidJsonAfter.json b/testlib/src/main/resources/json/invalidJsonAfter.json index e69de29bb2..8b13789179 100644 --- a/testlib/src/main/resources/json/invalidJsonAfter.json +++ b/testlib/src/main/resources/json/invalidJsonAfter.json @@ -0,0 +1 @@ + diff --git a/testlib/src/main/resources/json/notJsonAfter.json b/testlib/src/main/resources/json/notJsonAfter.json index e69de29bb2..8b13789179 100644 --- a/testlib/src/main/resources/json/notJsonAfter.json +++ b/testlib/src/main/resources/json/notJsonAfter.json @@ -0,0 +1 @@ + diff --git a/testlib/src/main/resources/json/singletonArrayAfter_Jackson.json b/testlib/src/main/resources/json/singletonArrayAfter_Jackson.json index 243bc2550b..8290d39198 100644 --- a/testlib/src/main/resources/json/singletonArrayAfter_Jackson.json +++ b/testlib/src/main/resources/json/singletonArrayAfter_Jackson.json @@ -1 +1 @@ -[ 1, 2, 3, 4 ] \ No newline at end of file +[ 1, 2, 3, 4 ] diff --git a/testlib/src/main/resources/json/sortByKeysAfter_Jackson.json b/testlib/src/main/resources/json/sortByKeysAfter_Jackson.json index 25ce5dd094..fe9c8364bc 100644 --- a/testlib/src/main/resources/json/sortByKeysAfter_Jackson.json +++ b/testlib/src/main/resources/json/sortByKeysAfter_Jackson.json @@ -16,4 +16,4 @@ "c" : 4, "x" : 5 } -} \ No newline at end of file +} diff --git a/testlib/src/main/resources/json/sortByKeysAfter_Jackson_spaceAfterKeySeparator.json b/testlib/src/main/resources/json/sortByKeysAfter_Jackson_spaceAfterKeySeparator.json index 25ce5dd094..fe9c8364bc 100644 --- a/testlib/src/main/resources/json/sortByKeysAfter_Jackson_spaceAfterKeySeparator.json +++ b/testlib/src/main/resources/json/sortByKeysAfter_Jackson_spaceAfterKeySeparator.json @@ -16,4 +16,4 @@ "c" : 4, "x" : 5 } -} \ No newline at end of file +} diff --git a/testlib/src/main/resources/npm/prettier/plugins/java-test.dirty b/testlib/src/main/resources/npm/prettier/plugins/java-test.dirty index ebadbfe112..43eb2039d6 100644 --- a/testlib/src/main/resources/npm/prettier/plugins/java-test.dirty +++ b/testlib/src/main/resources/npm/prettier/plugins/java-test.dirty @@ -1,6 +1,5 @@ import java.util.ArrayList; - import java.util.Arrays;import java.util.List; import java.util.function.Consumer; diff --git a/testlib/src/main/resources/protobuf/buf/buf.proto b/testlib/src/main/resources/protobuf/buf/buf.proto index a90d58bbd0..42d3a82853 100644 --- a/testlib/src/main/resources/protobuf/buf/buf.proto +++ b/testlib/src/main/resources/protobuf/buf/buf.proto @@ -2,4 +2,4 @@ message Testing { required string field1 = 1; required int32 field2 = 2; optional string field3 = 3; -} \ No newline at end of file +} diff --git a/testlib/src/main/resources/sql/dbeaver/sqlConfig2.properties b/testlib/src/main/resources/sql/dbeaver/sqlConfig2.properties index 4d1ac4c935..71bc0e0cff 100644 --- a/testlib/src/main/resources/sql/dbeaver/sqlConfig2.properties +++ b/testlib/src/main/resources/sql/dbeaver/sqlConfig2.properties @@ -1,4 +1,4 @@ sql.formatter.keyword.case=LOWER sql.formatter.statement.delimiter=; sql.formatter.indent.type=tab -sql.formatter.indent.size=2 \ No newline at end of file +sql.formatter.indent.size=2 diff --git a/testlib/src/main/resources/yaml/array_with_bracket.clean.yaml b/testlib/src/main/resources/yaml/array_with_bracket.clean.yaml index c6f891b9de..6080ba1f82 100644 --- a/testlib/src/main/resources/yaml/array_with_bracket.clean.yaml +++ b/testlib/src/main/resources/yaml/array_with_bracket.clean.yaml @@ -9,4 +9,4 @@ episodes: - 7 best-jedi: name: "Obi-Wan" - side: "light" \ No newline at end of file + side: "light" diff --git a/testlib/src/main/resources/yaml/array_with_bracket.yaml b/testlib/src/main/resources/yaml/array_with_bracket.yaml index e28373163d..c40f171f44 100644 --- a/testlib/src/main/resources/yaml/array_with_bracket.yaml +++ b/testlib/src/main/resources/yaml/array_with_bracket.yaml @@ -2,4 +2,4 @@ episodes: [1, 2, 3, 4, 5, 6, 7] -best-jedi: {name: Obi-Wan, side: light} \ No newline at end of file +best-jedi: {name: Obi-Wan, side: light} diff --git a/testlib/src/main/resources/yaml/separator_comments.clean.yaml b/testlib/src/main/resources/yaml/separator_comments.clean.yaml index 35bb8717dd..5cab4505e2 100644 --- a/testlib/src/main/resources/yaml/separator_comments.clean.yaml +++ b/testlib/src/main/resources/yaml/separator_comments.clean.yaml @@ -4,4 +4,4 @@ hr: - "Sammy Sosa" rbi: - "SS" -- "Ken Griffey" \ No newline at end of file +- "Ken Griffey" diff --git a/testlib/src/main/resources/yaml/separator_comments.yaml b/testlib/src/main/resources/yaml/separator_comments.yaml index 0213e66406..79c993f6e7 100644 --- a/testlib/src/main/resources/yaml/separator_comments.yaml +++ b/testlib/src/main/resources/yaml/separator_comments.yaml @@ -6,4 +6,4 @@ hr: - &SS Sammy Sosa rbi: - *SS # Subsequent occurrence - - Ken Griffey \ No newline at end of file + - Ken Griffey diff --git a/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java b/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java index ab7c8c277b..33d102b993 100644 --- a/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java @@ -31,9 +31,9 @@ import org.junit.jupiter.api.condition.EnabledOnOs; class FileSignatureTest extends ResourceHarness { - private final static String[] inputPaths = {"A", "C", "C", "A", "B"}; - private final static String[] expectedPathList = inputPaths; - private final static String[] expectedPathSet = {"A", "B", "C"}; + private static final String[] inputPaths = {"A", "C", "C", "A", "B"}; + private static final String[] expectedPathList = inputPaths; + private static final String[] expectedPathSet = {"A", "B", "C"}; @Test void testFromList() throws IOException { diff --git a/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java b/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java index 6356e02660..224d446608 100644 --- a/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java @@ -208,13 +208,13 @@ public FormatterSettingsAssert containsSpecificValuesOf(File file) { Properties settingsProps = actual.getProperties(); for (String expectedValue : VALID_VALUES) { // A parsable (valid) file contains keys of the following format - String validValueName = (null == expectedValue) ? "null" : expectedValue; + String validValueName = expectedValue == null ? "null" : expectedValue; String key = String.format("%s.%s", fileName, validValueName); if (!settingsProps.containsKey(key)) { failWithMessage("Key <%s> not part of formatter settings.", key); } String value = settingsProps.getProperty(key); - if ((null != expectedValue) && (!expectedValue.equals(value))) { + if ((expectedValue != null) && (!expectedValue.equals(value))) { failWithMessage("Value of key <%s> is '%s' and not '%s' as expected.", key, value, expectedValue); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/GitPrePushHookInstallerTest.java b/testlib/src/test/java/com/diffplug/spotless/GitPrePushHookInstallerTest.java index 0ac3fa2c1c..df2077b210 100644 --- a/testlib/src/test/java/com/diffplug/spotless/GitPrePushHookInstallerTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/GitPrePushHookInstallerTest.java @@ -29,7 +29,7 @@ import com.diffplug.spotless.GitPrePushHookInstaller.GitPreHookLogger; class GitPrePushHookInstallerTest extends ResourceHarness { - private final static String OS = System.getProperty("os.name"); + private static final String OS = System.getProperty("os.name"); private final List logs = new ArrayList<>(); private final GitPreHookLogger logger = new GitPreHookLogger() { diff --git a/testlib/src/test/java/com/diffplug/spotless/JvmTest.java b/testlib/src/test/java/com/diffplug/spotless/JvmTest.java index 801ca2ab24..9353f0fa9e 100644 --- a/testlib/src/test/java/com/diffplug/spotless/JvmTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/JvmTest.java @@ -43,8 +43,8 @@ void initialize() { @Test 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))); + Arrays.asList(differentVersions).forEach(v -> testSupport.add(v + Jvm.version(), v.toString())); + Arrays.asList(differentVersions).forEach(v -> assertThat(testSupport.toString()).contains(String.format("Version %d", v))); assertThat(testSupport.toString()).contains(String.format("%s alternatives", TEST_NAME)); } @@ -142,7 +142,7 @@ void supportProposesFormatterUpgrade() { }).getMessage(); assertThat(proposal.replace("\r", "")).isEqualTo("My Test Formatter " + fmtVersion + " is currently being used, but outdated.\n" + "My Test Formatter 2 is the recommended version, which may have fixed this problem.\n" + - "My Test Formatter 2 requires JVM " + (requiredJvm) + "+."); + "My Test Formatter 2 requires JVM " + requiredJvm + "+."); } }