From d3373b079083ef119c22760670eaf0ca9fa85ef3 Mon Sep 17 00:00:00 2001 From: Goooler Date: Sat, 11 Mar 2023 20:03:26 +0800 Subject: [PATCH] Java cleanups --- .../extra/EclipseBasedStepBuilder.java | 4 +- .../diffplug/spotless/extra/GitRatchet.java | 8 +-- .../spotless/extra/GitWorkarounds.java | 4 +- .../integration/DiffMessageFormatter.java | 2 +- .../extra/wtp/EclipseWtpFormatterStep.java | 22 +++---- .../spotless/extra/GitAttributesTest.java | 4 +- .../java/JavaCleanthatRefactorerFunc.java | 11 ++-- .../glue/json/AJacksonFormatterFunc.java | 5 +- .../glue/json/JacksonJsonFormatterFunc.java | 2 +- .../diffplug/spotless/EncodingErrorMsg.java | 6 +- .../diffplug/spotless/FeatureClassLoader.java | 7 +- .../com/diffplug/spotless/FileSignature.java | 10 +-- .../com/diffplug/spotless/ForeignExe.java | 4 +- .../spotless/FormatExceptionPolicy.java | 8 +-- .../com/diffplug/spotless/FormatterFunc.java | 8 +-- .../spotless/FormatterProperties.java | 7 +- .../com/diffplug/spotless/FormatterStep.java | 17 ++--- .../java/com/diffplug/spotless/JarState.java | 7 +- .../main/java/com/diffplug/spotless/Jvm.java | 16 ++--- .../com/diffplug/spotless/LineEnding.java | 4 +- .../com/diffplug/spotless/MoreIterables.java | 5 +- .../java/com/diffplug/spotless/NoLambda.java | 6 +- .../com/diffplug/spotless/ProcessRunner.java | 10 +-- .../com/diffplug/spotless/Provisioner.java | 6 +- .../spotless/SerializableFileFilter.java | 4 +- .../spotless/SerializableFileFilterImpl.java | 4 +- .../com/diffplug/spotless/SpotlessCache.java | 4 +- .../diffplug/spotless/cpp/CppDefaults.java | 13 ++-- .../spotless/generic/EndWithNewlineStep.java | 7 +- .../spotless/generic/LicenseHeaderStep.java | 4 +- .../spotless/generic/PipeStepPair.java | 4 +- .../spotless/java/CleanthatJavaStep.java | 8 +-- .../spotless/java/FormatAnnotationsStep.java | 4 +- .../spotless/npm/NodeServerLayout.java | 5 +- .../spotless/npm/NpmResourceHelper.java | 2 +- .../spotless/npm/PrettierFormatterStep.java | 4 +- .../npm/PrettierMissingParserException.java | 2 +- .../spotless/npm/SimpleRestClient.java | 5 +- .../diffplug/spotless/pom/SortPomStep.java | 4 +- .../DBeaverSQLFormatterConfiguration.java | 8 +-- .../spotless/sql/dbeaver/FormatterToken.java | 14 ++-- .../spotless/sql/dbeaver/SQLDialect.java | 6 +- .../sql/dbeaver/SQLTokenizedFormatter.java | 13 ++-- .../spotless/sql/dbeaver/SQLTokensParser.java | 14 ++-- .../gradle/spotless/AJacksonGradleConfig.java | 2 +- .../gradle/spotless/FormatExtension.java | 19 ++---- .../gradle/spotless/GradleProvisioner.java | 4 +- .../gradle/spotless/JavaExtension.java | 4 +- .../gradle/spotless/JavascriptExtension.java | 2 +- .../gradle/spotless/JsonExtension.java | 2 +- .../gradle/spotless/JvmLocalCache.java | 14 ++-- .../spotless/RegisterDependenciesTask.java | 4 +- .../spotless/SpotlessExtensionImpl.java | 20 +++--- .../spotless/SpotlessExtensionPredeclare.java | 20 +++--- .../spotless/SpotlessPluginRedirect.java | 4 +- .../gradle/spotless/SpotlessTask.java | 6 +- .../gradle/spotless/SpotlessTaskImpl.java | 2 +- .../gradle/spotless/SpotlessTaskService.java | 4 +- .../gradle/spotless/YamlExtension.java | 2 +- .../spotless/DiffMessageFormatterTest.java | 12 ++-- .../gradle/spotless/GitRatchetGradleTest.java | 7 +- .../GradleIncrementalResolutionTest.java | 6 +- .../spotless/GradleIntegrationHarness.java | 4 +- .../diffplug/gradle/spotless/IdeHookTest.java | 4 +- .../gradle/spotless/MultiProjectTest.java | 4 +- .../NpmInstallCacheIntegrationTests.java | 3 +- .../gradle/spotless/PaddedCellTaskTest.java | 18 ++--- .../spotless/maven/ArtifactResolver.java | 6 +- .../spotless/maven/FormatterFactory.java | 2 +- .../spotless/maven/cpp/EclipseCdt.java | 6 +- .../spotless/maven/groovy/GrEclipse.java | 6 +- .../diffplug/spotless/maven/java/Eclipse.java | 6 +- .../npm/AbstractNpmFormatterStepFactory.java | 9 +-- .../diffplug/spotless/maven/MavenRunner.java | 2 +- .../com/diffplug/spotless/ReflectionUtil.java | 4 +- .../diffplug/spotless/ResourceHarness.java | 10 +-- .../spotless/SerializableEqualityTester.java | 31 ++++----- .../diffplug/spotless/TestProvisioner.java | 18 ++--- .../spotless/EncodingErrorMsgTest.java | 4 +- .../spotless/FormatterPropertiesTest.java | 4 +- .../com/diffplug/spotless/FormatterTest.java | 2 +- .../java/com/diffplug/spotless/JvmTest.java | 66 +++++++------------ .../spotless/LazyForwardingEqualityTest.java | 4 +- .../spotless/generic/PipeStepPairTest.java | 4 +- .../java/FormatAnnotationsStepTest.java | 3 +- .../java/GoogleJavaFormatStepTest.java | 6 +- .../spotless/markdown/FreshMarkStepTest.java | 2 +- .../spotless/npm/SimpleJsonWriterTest.java | 4 +- .../spotless/scala/ScalaFmtStepTest.java | 5 +- 89 files changed, 301 insertions(+), 382 deletions(-) diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/EclipseBasedStepBuilder.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/EclipseBasedStepBuilder.java index 4f48a5ed74..f2a9430052 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/EclipseBasedStepBuilder.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/EclipseBasedStepBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,7 +60,7 @@ public class EclipseBasedStepBuilder { */ private static final String ECLIPSE_FORMATTER_RESOURCES = EclipseBasedStepBuilder.class.getPackage().getName().replace('.', '/'); - private List dependencies = new ArrayList<>(); + private final List dependencies = new ArrayList<>(); private Iterable settingsFiles = new ArrayList<>(); /** Initialize valid default configuration, taking latest version */ 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..4ef04dc3af 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 @@ -62,7 +62,7 @@ public boolean isClean(Project project, ObjectId treeSha, File file) throws IOEx return isClean(project, treeSha, relativePath); } - private Map dirCaches = new HashMap<>(); + private final Map dirCaches = new HashMap<>(); /** * This is the highest-level method, which all the others serve. Given the sha @@ -136,9 +136,9 @@ private static boolean worktreeIsCleanCheckout(TreeWalk treeWalk) { private final static int INDEX = 1; private final static int WORKDIR = 2; - Map gitRoots = new HashMap<>(); - Table rootTreeShaCache = HashBasedTable.create(); - Map subtreeShaCache = new HashMap<>(); + final Map gitRoots = new HashMap<>(); + final Table rootTreeShaCache = HashBasedTable.create(); + final Map subtreeShaCache = new HashMap<>(); /** * The first part of making this fast is finding the appropriate git repository quickly. Because of composite diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitWorkarounds.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitWorkarounds.java index 70f0b9cb99..7c38ac1303 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitWorkarounds.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitWorkarounds.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2022 DiffPlug + * Copyright 2020-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -107,7 +107,7 @@ static class RepositorySpecificResolver extends FileRepositoryBuilder { private File commonDirectory; - private Config baseConfig; + private final Config baseConfig; public RepositorySpecificResolver() { this(null); 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 55336e8c04..5d9ae6d0ec 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 @@ -267,7 +267,7 @@ private static String diffWhitespaceLineEndings(String dirty, String clean, bool try (DiffFormatter formatter = new DiffFormatter(out)) { formatter.format(edits, a, b); } - String formatted = out.toString(StandardCharsets.UTF_8.name()); + String formatted = out.toString(StandardCharsets.UTF_8); // we don't need the diff to show this, since we display newlines ourselves formatted = formatted.replace("\\ No newline at end of file\n", ""); 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..8e9c98375e 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStep.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,6 @@ */ package com.diffplug.spotless.extra.wtp; -import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Properties; @@ -50,7 +49,7 @@ public enum EclipseWtpFormatterStep { } public EclipseBasedStepBuilder createBuilder(Provisioner provisioner) { - return new EclipseBasedStepBuilder(NAME, " - " + toString(), provisioner, state -> formatterCall.apply(implementationClassName, state)); + return new EclipseBasedStepBuilder(NAME, " - " + this, provisioner, state -> formatterCall.apply(implementationClassName, state)); } public static String defaultVersion() { @@ -78,16 +77,13 @@ private static FormatterFunc applyWithFile(String className, EclipseBasedStepBui Class formatterClazz = state.loadClass(FORMATTER_PACKAGE + className); Object formatter = formatterClazz.getConstructor(Properties.class).newInstance(state.getPreferences()); Method method = formatterClazz.getMethod(FORMATTER_METHOD, String.class, String.class); - return JVM_SUPPORT.suggestLaterVersionOnError(state.getSemanticVersion(), new FormatterFunc.NeedsFile() { - @Override - public String applyWithFile(String unix, File file) throws Exception { - try { - 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; - } + return JVM_SUPPORT.suggestLaterVersionOnError(state.getSemanticVersion(), (FormatterFunc.NeedsFile) (unix, file) -> { + try { + 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; } }); } diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/GitAttributesTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/GitAttributesTest.java index a7cde9e58f..8c1444c99c 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/GitAttributesTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/GitAttributesTest.java @@ -83,7 +83,7 @@ void policyTest() { setFile(".gitattributes").toContent(StringPrinter.buildStringFromLines( "* eol=lf", "*.MF eol=crlf")); - LineEnding.Policy policy = LineEnding.GIT_ATTRIBUTES.createPolicy(rootFolder(), () -> testFiles()); + LineEnding.Policy policy = LineEnding.GIT_ATTRIBUTES.createPolicy(rootFolder(), this::testFiles); Assertions.assertThat(policy.getEndingFor(newFile("someFile"))).isEqualTo("\n"); Assertions.assertThat(policy.getEndingFor(newFile("subfolder/someFile"))).isEqualTo("\n"); Assertions.assertThat(policy.getEndingFor(newFile("MANIFEST.MF"))).isEqualTo("\r\n"); @@ -98,7 +98,7 @@ void policyDefaultLineEndingTest() throws GitAPIException { "[core]", "autocrlf=true", "eol=lf")); - LineEnding.Policy policy = LineEnding.GIT_ATTRIBUTES.createPolicy(rootFolder(), () -> testFiles()); + LineEnding.Policy policy = LineEnding.GIT_ATTRIBUTES.createPolicy(rootFolder(), this::testFiles); Assertions.assertThat(policy.getEndingFor(newFile("someFile"))).isEqualTo("\r\n"); } diff --git a/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java b/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java index d7148f8892..f25a6a1d16 100644 --- a/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java +++ b/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java @@ -16,7 +16,6 @@ package com.diffplug.spotless.glue.java; import java.io.IOException; -import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -39,10 +38,10 @@ public class JavaCleanthatRefactorerFunc implements FormatterFunc { private static final Logger LOGGER = LoggerFactory.getLogger(JavaCleanthatRefactorerFunc.class); - private String jdkVersion; - private List included; - private List excluded; - private boolean includeDraft; + private final String jdkVersion; + private final List included; + private final List excluded; + private final boolean includeDraft; public JavaCleanthatRefactorerFunc(String jdkVersion, List included, List excluded, boolean includeDraft) { this.jdkVersion = jdkVersion == null ? IJdkVersionConstants.JDK_8 : jdkVersion; @@ -52,7 +51,7 @@ public JavaCleanthatRefactorerFunc(String jdkVersion, List included, Lis } public JavaCleanthatRefactorerFunc() { - this(IJdkVersionConstants.JDK_8, Arrays.asList("SafeAndConsensual"), Arrays.asList(), false); + this(IJdkVersionConstants.JDK_8, List.of("SafeAndConsensual"), List.of(), false); } @Override diff --git a/lib/src/jackson/java/com/diffplug/spotless/glue/json/AJacksonFormatterFunc.java b/lib/src/jackson/java/com/diffplug/spotless/glue/json/AJacksonFormatterFunc.java index 1f317fa3b4..3b9f28236f 100644 --- a/lib/src/jackson/java/com/diffplug/spotless/glue/json/AJacksonFormatterFunc.java +++ b/lib/src/jackson/java/com/diffplug/spotless/glue/json/AJacksonFormatterFunc.java @@ -32,7 +32,7 @@ */ // https://github.com/FasterXML/jackson-dataformats-text/issues/372 public abstract class AJacksonFormatterFunc implements FormatterFunc { - private JacksonConfig jacksonConfig; + private final JacksonConfig jacksonConfig; public AJacksonFormatterFunc(JacksonConfig jacksonConfig) { this.jacksonConfig = jacksonConfig; @@ -49,9 +49,8 @@ protected String format(ObjectMapper objectMapper, String input) throws IllegalA try { // ObjectNode is not compatible with SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS Object objectNode = objectMapper.readValue(input, inferType(input)); - String output = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectNode); - return output; + return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectNode); } catch (JsonProcessingException e) { throw new IllegalArgumentException("Unable to format. input='" + input + "'", e); } 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..52ee8ae4e0 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 @@ -33,7 +33,7 @@ */ // https://github.com/FasterXML/jackson-dataformats-text/issues/372 public class JacksonJsonFormatterFunc extends AJacksonFormatterFunc { - private JacksonJsonConfig jacksonConfig; + private final JacksonJsonConfig jacksonConfig; public JacksonJsonFormatterFunc(JacksonJsonConfig jacksonConfig) { super(jacksonConfig); diff --git a/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java b/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java index 3e4bb3423b..ebd23a0ce3 100644 --- a/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java +++ b/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java @@ -31,7 +31,7 @@ class EncodingErrorMsg { static final char UNREPRESENTABLE = '�'; - private static int CONTEXT = 3; + private static final int CONTEXT = 3; static @Nullable String msg(String chars, byte[] bytes, Charset charset) { int unrepresentable = chars.indexOf(UNREPRESENTABLE); @@ -70,7 +70,7 @@ private EncodingErrorMsg(String chars, ByteBuffer byteBuf, Charset charset, int if (charset.equals(StandardCharsets.UTF_8)) { message.append("Spotless uses UTF-8 by default."); } else { - message.append("You configured Spotless to use " + charset.name() + "."); + message.append("You configured Spotless to use ").append(charset.name()).append("."); } int line = 1; @@ -84,7 +84,7 @@ private EncodingErrorMsg(String chars, ByteBuffer byteBuf, Charset charset, int ++col; } } - message.append(" At line " + line + " col " + col + ":"); + message.append(" At line ").append(line).append(" col ").append(col).append(":"); // https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html LinkedHashSet encodings = new LinkedHashSet<>(); diff --git a/lib/src/main/java/com/diffplug/spotless/FeatureClassLoader.java b/lib/src/main/java/com/diffplug/spotless/FeatureClassLoader.java index 0703a91318..bc952e6274 100644 --- a/lib/src/main/java/com/diffplug/spotless/FeatureClassLoader.java +++ b/lib/src/main/java/com/diffplug/spotless/FeatureClassLoader.java @@ -83,11 +83,8 @@ protected Class findClass(String name) throws ClassNotFoundException { private static boolean useBuildToolClassLoader(String name) { if (name.startsWith("org.slf4j.")) { return true; - } else if (!name.startsWith("com.diffplug.spotless.extra") && name.startsWith("com.diffplug.spotless.")) { - return true; - } else { - return false; - } + } else + return !name.startsWith("com.diffplug.spotless.extra") && name.startsWith("com.diffplug.spotless."); } @Override diff --git a/lib/src/main/java/com/diffplug/spotless/FileSignature.java b/lib/src/main/java/com/diffplug/spotless/FileSignature.java index 59893f26e6..213fbf02e5 100644 --- a/lib/src/main/java/com/diffplug/spotless/FileSignature.java +++ b/lib/src/main/java/com/diffplug/spotless/FileSignature.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ public static FileSignature signAsSet(Iterable files) throws IOException { StringBuilder builder = new StringBuilder(); builder.append("For these files:\n"); for (File file : files) { - builder.append(" " + file.getAbsolutePath() + "\n"); + builder.append(" ").append(file.getAbsolutePath()).append("\n"); } builder.append("a caching signature is being generated, which will be based only on their\n"); builder.append("names, not their full path (foo.txt, not C:\folder\foo.txt). Unexpectedly,\n"); @@ -107,7 +107,7 @@ public File getOnlyFile() { } } - private static boolean machineIsWin = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win"); + private static final boolean machineIsWin = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win"); /** Returns true if this JVM is running on a windows machine. */ public static boolean machineIsWin() { @@ -143,11 +143,11 @@ private static List validateInputFiles(List files) { static final Cache cache = new Cache(); private static final class Cache { - Map cache = new HashMap<>(); + final Map cache = new HashMap<>(); synchronized Sig sign(File fileInput) throws IOException { String canonicalPath = fileInput.getCanonicalPath(); - Sig sig = cache.computeIfAbsent(canonicalPath, ThrowingEx. wrap(p -> { + Sig sig = cache.computeIfAbsent(canonicalPath, ThrowingEx.wrap(p -> { MessageDigest digest = MessageDigest.getInstance("SHA-256"); File file = new File(p); // calculate the size and content hash of the file diff --git a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java index d1f8abd3ee..f6a0025409 100644 --- a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java +++ b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 DiffPlug + * Copyright 2020-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -129,7 +129,7 @@ private RuntimeException exceptionFmt(String msgPrimary, ProcessRunner.Result cm errorMsg.append(msgFix); errorMsg.append('\n'); } - errorMsg.append(cmd.toString()); + errorMsg.append(cmd); return new RuntimeException(errorMsg.toString()); } } diff --git a/lib/src/main/java/com/diffplug/spotless/FormatExceptionPolicy.java b/lib/src/main/java/com/diffplug/spotless/FormatExceptionPolicy.java index da23f74432..94e4daae96 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatExceptionPolicy.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatExceptionPolicy.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ /** A policy for handling exceptions in the format. */ public interface FormatExceptionPolicy extends Serializable, NoLambda { /** Called for every error in the formatter. */ - public void handleError(Throwable e, FormatterStep step, String relativePath); + void handleError(Throwable e, FormatterStep step, String relativePath); /** * Returns a byte array representation of everything inside this {@code FormatExceptionPolicy}. @@ -28,12 +28,12 @@ public interface FormatExceptionPolicy extends Serializable, NoLambda { * The main purpose of this method is to ensure one can't instantiate this class with lambda * expressions, which are notoriously difficult to serialize and deserialize properly. */ - public byte[] toBytes(); + byte[] toBytes(); /** * A policy which rethrows subclasses of {@code Error} and logs other kinds of Exception. */ - public static FormatExceptionPolicy failOnlyOnError() { + static FormatExceptionPolicy failOnlyOnError() { return new FormatExceptionPolicyLegacy(); } } diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterFunc.java b/lib/src/main/java/com/diffplug/spotless/FormatterFunc.java index 14b407a2eb..559cf19e80 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatterFunc.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatterFunc.java @@ -50,7 +50,7 @@ interface Closeable extends FormatterFunc, AutoCloseable { * The bug (and its fix) which is easy to write using this method: https://github.com/diffplug/spotless/commit/7f16ecca031810b5e6e6f647e1f10a6d2152d9f4 * How the {@code of()} methods below make the correct thing easier to write and safer: https://github.com/diffplug/spotless/commit/18c10f9c93d6f18f753233d0b5f028d5f0961916 */ - public static Closeable ofDangerous(AutoCloseable closeable, FormatterFunc function) { + static Closeable ofDangerous(AutoCloseable closeable, FormatterFunc function) { Objects.requireNonNull(closeable, "closeable"); Objects.requireNonNull(function, "function"); return new Closeable() { @@ -73,7 +73,7 @@ public String apply(String unix) throws Exception { /** @deprecated synonym for {@link #ofDangerous(AutoCloseable, FormatterFunc)} */ @Deprecated - public static Closeable of(AutoCloseable closeable, FormatterFunc function) { + static Closeable of(AutoCloseable closeable, FormatterFunc function) { return ofDangerous(closeable, function); } @@ -83,7 +83,7 @@ interface ResourceFunc { } /** Creates a {@link FormatterFunc.Closeable} which uses the given resource to execute the format function. */ - public static Closeable of(T resource, ResourceFunc function) { + static Closeable of(T resource, ResourceFunc function) { Objects.requireNonNull(resource, "resource"); Objects.requireNonNull(function, "function"); return new Closeable() { @@ -110,7 +110,7 @@ interface ResourceFuncNeedsFile { } /** Creates a {@link FormatterFunc.Closeable} which uses the given resource to execute the file-dependent format function. */ - public static Closeable of(T resource, ResourceFuncNeedsFile function) { + static Closeable of(T resource, ResourceFuncNeedsFile function) { Objects.requireNonNull(resource, "resource"); Objects.requireNonNull(function, "function"); return new Closeable() { diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java b/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java index 81fa6a93cf..7445f6f284 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -205,9 +205,8 @@ protected Properties execute(final File xmlFile, final Node rootNode) protected Properties execute(File file, Node rootNode) throws IOException, IllegalArgumentException { final Properties properties = new Properties(); Node firstProfile = getSingleProfile(rootNode); - for (Object settingObj : getChildren(firstProfile, "setting")) { - Node setting = (Node) settingObj; - NamedNodeMap attributes = setting.getAttributes(); + for (Node settingObj : getChildren(firstProfile, "setting")) { + NamedNodeMap attributes = settingObj.getAttributes(); Node id = attributes.getNamedItem("id"); Node value = attributes.getNamedItem("value"); if (null == id) { diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterStep.java b/lib/src/main/java/com/diffplug/spotless/FormatterStep.java index ce09f68450..c88880504b 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatterStep.java @@ -29,7 +29,7 @@ */ public interface FormatterStep extends Serializable { /** The name of the step, for debugging purposes. */ - public String getName(); + String getName(); /** * Returns a formatted version of the given content. @@ -43,7 +43,8 @@ public interface FormatterStep extends Serializable { * if the formatter step doesn't have any changes to make * @throws Exception if the formatter step experiences a problem */ - public @Nullable String format(String rawUnix, File file) throws Exception; + @Nullable + String format(String rawUnix, File file) throws Exception; /** * Returns a new FormatterStep which will only apply its changes @@ -53,7 +54,7 @@ public interface FormatterStep extends Serializable { * java regular expression used to filter out files which content doesn't contain pattern * @return FormatterStep */ - public default FormatterStep filterByContentPattern(String contentPattern) { + default FormatterStep filterByContentPattern(String contentPattern) { return new FilterByContentPatternFormatterStep(this, contentPattern); } @@ -63,7 +64,7 @@ public default FormatterStep filterByContentPattern(String contentPattern) { * * The provided filter must be serializable. */ - public default FormatterStep filterByFile(SerializableFileFilter filter) { + default FormatterStep filterByFile(SerializableFileFilter filter) { return new FilterByFileFormatterStep(this, filter); } @@ -100,7 +101,7 @@ public final String format(String rawUnix, File file) throws Exception { * only the state supplied by state and nowhere else. * @return A FormatterStep */ - public static FormatterStep createLazy( + static FormatterStep createLazy( String name, ThrowingEx.Supplier stateSupplier, ThrowingEx.Function stateToFormatter) { @@ -117,7 +118,7 @@ public static FormatterStep createLazy( * only the state supplied by state and nowhere else. * @return A FormatterStep */ - public static FormatterStep create( + static FormatterStep create( String name, State state, ThrowingEx.Function stateToFormatter) { @@ -134,7 +135,7 @@ public static FormatterStep create( * @return A FormatterStep which will never report that it is up-to-date, because * it is not equal to the serialized representation of itself. */ - public static FormatterStep createNeverUpToDateLazy( + static FormatterStep createNeverUpToDateLazy( String name, ThrowingEx.Supplier functionSupplier) { return new FormatterStepImpl.NeverUpToDate(name, functionSupplier); @@ -148,7 +149,7 @@ public static FormatterStep createNeverUpToDateLazy( * @return A FormatterStep which will never report that it is up-to-date, because * it is not equal to the serialized representation of itself. */ - public static FormatterStep createNeverUpToDate( + static FormatterStep createNeverUpToDate( String name, FormatterFunc function) { Objects.requireNonNull(function, "function"); diff --git a/lib/src/main/java/com/diffplug/spotless/JarState.java b/lib/src/main/java/com/diffplug/spotless/JarState.java index abe595e608..cc30590ed2 100644 --- a/lib/src/main/java/com/diffplug/spotless/JarState.java +++ b/lib/src/main/java/com/diffplug/spotless/JarState.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,6 @@ import java.util.Objects; import java.util.Set; import java.util.TreeSet; -import java.util.stream.Collectors; /** * Grabs a jar and its dependencies from maven, @@ -43,7 +42,7 @@ public final class JarState implements Serializable { private final FileSignature fileSignature; private JarState(Collection mavenCoordinates, FileSignature fileSignature) { - this.mavenCoordinates = new TreeSet(mavenCoordinates); + this.mavenCoordinates = new TreeSet<>(mavenCoordinates); this.fileSignature = fileSignature; } @@ -67,7 +66,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(mavenCoordinates, fileSignature); diff --git a/lib/src/main/java/com/diffplug/spotless/Jvm.java b/lib/src/main/java/com/diffplug/spotless/Jvm.java index c9c71b72df..fea7326345 100644 --- a/lib/src/main/java/com/diffplug/spotless/Jvm.java +++ b/lib/src/main/java/com/diffplug/spotless/Jvm.java @@ -67,14 +67,14 @@ public static class Support { private final NavigableMap fmt2jvmVersion; private Support(String fromatterName) { - this(fromatterName, new SemanticVersionComparator()); + this(fromatterName, new SemanticVersionComparator<>()); } private Support(String formatterName, Comparator formatterVersionComparator) { fmtName = formatterName; fmtVersionComparator = formatterVersionComparator; - jvm2fmtVersion = new TreeMap(); - fmt2jvmVersion = new TreeMap(formatterVersionComparator); + jvm2fmtVersion = new TreeMap<>(); + fmt2jvmVersion = new TreeMap<>(formatterVersionComparator); } /** @@ -125,7 +125,7 @@ public void assertFormatterSupported(V formatterVersion) { private String buildUnsupportedFormatterMessage(V fmtVersion) { int requiredJvmVersion = getRequiredJvmVersion(fmtVersion); if (Jvm.version() < requiredJvmVersion) { - return buildUpgradeJvmMessage(fmtVersion) + "Upgrade your JVM or try " + toString(); + return buildUpgradeJvmMessage(fmtVersion) + "Upgrade your JVM or try " + this; } return ""; } @@ -228,7 +228,7 @@ public int compare(V version0, V version1) { Objects.requireNonNull(version1); int[] version0Items = convert(version0); int[] version1Items = convert(version1); - int numberOfElements = version0Items.length > version1Items.length ? version0Items.length : version1Items.length; + int numberOfElements = Math.max(version0Items.length, version1Items.length); version0Items = Arrays.copyOf(version0Items, numberOfElements); version1Items = Arrays.copyOf(version1Items, numberOfElements); for (int i = 0; i < numberOfElements; i++) { @@ -243,12 +243,12 @@ public int compare(V version0, V version1) { private static int[] convert(V versionObject) { try { - return Arrays.asList(versionObject.toString().split("\\.")).stream().mapToInt(Integer::parseInt).toArray(); + return Arrays.stream(versionObject.toString().split("\\.")).mapToInt(Integer::parseInt).toArray(); } catch (Exception e) { throw new IllegalArgumentException(String.format("Not a semantic version: %s", versionObject), e); } } - }; + } } /** @@ -259,6 +259,6 @@ private static int[] convert(V versionObject) { */ public static Support support(String formatterName) { Objects.requireNonNull(formatterName); - return new Support(formatterName); + return new Support<>(formatterName); } } diff --git a/lib/src/main/java/com/diffplug/spotless/LineEnding.java b/lib/src/main/java/com/diffplug/spotless/LineEnding.java index 72b2532f2a..adaaf7f5e9 100644 --- a/lib/src/main/java/com/diffplug/spotless/LineEnding.java +++ b/lib/src/main/java/com/diffplug/spotless/LineEnding.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -133,7 +133,7 @@ public interface Policy extends Serializable, NoLambda { String getEndingFor(File file); /** Returns true iff this file has unix line endings. */ - public default boolean isUnix(File file) { + default boolean isUnix(File file) { Objects.requireNonNull(file); String ending = getEndingFor(file); return ending.equals(UNIX.str()); diff --git a/lib/src/main/java/com/diffplug/spotless/MoreIterables.java b/lib/src/main/java/com/diffplug/spotless/MoreIterables.java index c3b0e5f286..2b6e5efa60 100644 --- a/lib/src/main/java/com/diffplug/spotless/MoreIterables.java +++ b/lib/src/main/java/com/diffplug/spotless/MoreIterables.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; @@ -47,7 +46,7 @@ static > List toSortedSet(Iterable raw) { static List toSortedSet(Iterable raw, Comparator comparator) { List toBeSorted = toNullHostileList(raw); // sort it - Collections.sort(toBeSorted, comparator); + toBeSorted.sort(comparator); // remove any duplicates (normally there won't be any) if (toBeSorted.size() > 1) { Iterator iter = toBeSorted.iterator(); diff --git a/lib/src/main/java/com/diffplug/spotless/NoLambda.java b/lib/src/main/java/com/diffplug/spotless/NoLambda.java index ce326a6ceb..a462660460 100644 --- a/lib/src/main/java/com/diffplug/spotless/NoLambda.java +++ b/lib/src/main/java/com/diffplug/spotless/NoLambda.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,10 +40,10 @@ public interface NoLambda extends Serializable { * {@code SerializableFileFilterImpl.SkipFilesNamed} for an example of how to make a serializable * subclass.) */ - public byte[] toBytes(); + byte[] toBytes(); /** An implementation of NoLambda in which equality is based on the serialized representation of itself. */ - public static abstract class EqualityBasedOnSerialization implements NoLambda { + abstract 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 4e48042184..28c2646a96 100644 --- a/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java +++ b/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java @@ -254,18 +254,18 @@ public String assertExitZero(Charset charset) { @Override public String toString() { StringBuilder builder = new StringBuilder(); - builder.append("> arguments: " + args + "\n"); - builder.append("> exit code: " + exitCode + "\n"); + builder.append("> arguments: ").append(args).append("\n"); + builder.append("> exit code: ").append(exitCode).append("\n"); BiConsumer perStream = (name, content) -> { String string = new String(content, Charset.defaultCharset()).trim(); if (string.isEmpty()) { - builder.append("> " + name + ": (empty)\n"); + builder.append("> ").append(name).append(": (empty)\n"); } else { String[] lines = string.replace("\r", "").split("\n"); if (lines.length == 1) { - builder.append("> " + name + ": " + lines[0] + "\n"); + builder.append("> ").append(name).append(": ").append(lines[0]).append("\n"); } else { - builder.append("> " + name + ": (below)\n"); + builder.append("> ").append(name).append(": (below)\n"); for (String line : lines) { builder.append("> "); builder.append(line); diff --git a/lib/src/main/java/com/diffplug/spotless/Provisioner.java b/lib/src/main/java/com/diffplug/spotless/Provisioner.java index 259cac5a7c..0a18045e65 100644 --- a/lib/src/main/java/com/diffplug/spotless/Provisioner.java +++ b/lib/src/main/java/com/diffplug/spotless/Provisioner.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ public interface Provisioner { * Given a set of Maven coordinates, returns a set of jars which include all * of the specified coordinates and optionally their transitive dependencies. */ - public default Set provisionWithTransitives(boolean withTransitives, String... mavenCoordinates) { + default Set provisionWithTransitives(boolean withTransitives, String... mavenCoordinates) { return provisionWithTransitives(withTransitives, Arrays.asList(mavenCoordinates)); } @@ -37,5 +37,5 @@ public default Set provisionWithTransitives(boolean withTransitives, Strin * Given a set of Maven coordinates, returns a set of jars which include all * of the specified coordinates and optionally their transitive dependencies. */ - public Set provisionWithTransitives(boolean withTransitives, Collection mavenCoordinates); + Set provisionWithTransitives(boolean withTransitives, Collection mavenCoordinates); } diff --git a/lib/src/main/java/com/diffplug/spotless/SerializableFileFilter.java b/lib/src/main/java/com/diffplug/spotless/SerializableFileFilter.java index 6b5c16df64..de7ce4d612 100644 --- a/lib/src/main/java/com/diffplug/spotless/SerializableFileFilter.java +++ b/lib/src/main/java/com/diffplug/spotless/SerializableFileFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ /** A file filter with full support for serialization. */ public interface SerializableFileFilter extends FileFilter, Serializable, NoLambda { /** Creates a FileFilter which will accept all files except files with the given name(s). */ - public static SerializableFileFilter skipFilesNamed(String... names) { + static SerializableFileFilter skipFilesNamed(String... names) { return new SerializableFileFilterImpl.SkipFilesNamed(names); } } diff --git a/lib/src/main/java/com/diffplug/spotless/SerializableFileFilterImpl.java b/lib/src/main/java/com/diffplug/spotless/SerializableFileFilterImpl.java index f3a8f1f18d..2caecd1e44 100644 --- a/lib/src/main/java/com/diffplug/spotless/SerializableFileFilterImpl.java +++ b/lib/src/main/java/com/diffplug/spotless/SerializableFileFilterImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ static class SkipFilesNamed extends NoLambda.EqualityBasedOnSerialization implem SkipFilesNamed(String... namesToSkip) { Objects.requireNonNull(namesToSkip); List sorted = toSortedSet(Arrays.asList(namesToSkip)); - this.namesToSkip = sorted.toArray(new String[sorted.size()]); + this.namesToSkip = sorted.toArray(new String[0]); } @Override diff --git a/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java b/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java index 237e326482..a3b826db65 100644 --- a/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java +++ b/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java @@ -51,13 +51,13 @@ static final class SerializedKey { } @Override - public final boolean equals(Object other) { + public boolean equals(Object other) { return other instanceof SerializedKey && Arrays.equals(serialized, ((SerializedKey) other).serialized); } @Override - public final int hashCode() { + public int hashCode() { return hashCode; } } diff --git a/lib/src/main/java/com/diffplug/spotless/cpp/CppDefaults.java b/lib/src/main/java/com/diffplug/spotless/cpp/CppDefaults.java index cf31b4a95c..cabc2077ad 100644 --- a/lib/src/main/java/com/diffplug/spotless/cpp/CppDefaults.java +++ b/lib/src/main/java/com/diffplug/spotless/cpp/CppDefaults.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,20 +15,20 @@ */ package com.diffplug.spotless.cpp; -import java.util.Arrays; import java.util.stream.Collectors; +import java.util.stream.Stream; /** Common utilities for C/C++ */ public class CppDefaults { //Prevent instantiation - private CppDefaults() {}; + private CppDefaults() {} /** * Default delimiter expression shall cover most valid and common starts of C/C++ declarations and definitions. * Furthermore it shall not conflict with terms commonly used within license headers. * Note that the longest match is selected. Hence "using namespace foo" is preferred over "namespace foo". */ - public static final String DELIMITER_EXPR = Arrays.asList( + public static final String DELIMITER_EXPR = Stream.of( "#define", "#error", "#if", "#ifdef", "#ifndef", "#include", "#pragma", "#undef", "asm", "class", "namespace", "struct", "typedef", "using namespace", "const", "extern", "mutable", "signed", "unsigned", "volatile", @@ -37,8 +37,7 @@ public class CppDefaults { "int8_t", "int16_t", "int32_t", "int64_t", "__int8_t", "__int16_t", "__int32_t", "__int64_t", "uint8_t", "uint16_t", "uint32_t", "uint64_t") - .stream().map(s -> { - return "(? "(? { - return (String) formatterMethod.invoke(formatter, input); - }); + return JVM_SUPPORT.suggestLaterVersionOnError(version, input -> (String) formatterMethod.invoke(formatter, input)); } else { - return input -> { - return (String) formatterMethod.invoke(formatter, input); - }; + return input -> (String) formatterMethod.invoke(formatter, input); } } 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 5a2d856850..2118b347aa 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java @@ -428,11 +428,11 @@ private static final class State implements Serializable { */ State(List addedTypeAnnotations, List removedTypeAnnotations) { typeAnnotations.addAll(addedTypeAnnotations); - typeAnnotations.removeAll(removedTypeAnnotations); + removedTypeAnnotations.forEach(typeAnnotations::remove); } FormatterFunc toFormatter() { - return unixStr -> fixupTypeAnnotations(unixStr); + return this::fixupTypeAnnotations; } /** 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 850ea4eb6b..3148ccc31b 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java @@ -81,11 +81,8 @@ public boolean isLayoutPrepared() { if (!packageLockJsonFile.isFile()) { return false; } - if (!serveJsFile().isFile()) { - return false; - } // npmrc is optional, so must not be checked here - return true; + return serveJsFile().isFile(); } public boolean isNodeModulesPrepared() { diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java index 7a28685de0..db6bcf64df 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java @@ -82,7 +82,7 @@ static String readUtf8StringFromInputStream(InputStream input) { while ((numRead = input.read(buffer)) != -1) { output.write(buffer, 0, numRead); } - return output.toString(StandardCharsets.UTF_8.name()); + return output.toString(StandardCharsets.UTF_8); } catch (IOException e) { throw ThrowingEx.asRuntime(e); } 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 11a6230e4c..1b5765ca17 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java @@ -41,11 +41,11 @@ public class PrettierFormatterStep { public static final String NAME = "prettier-format"; - public static final Map defaultDevDependencies() { + public static Map defaultDevDependencies() { return defaultDevDependenciesWithPrettier("2.8.1"); } - public static final Map defaultDevDependenciesWithPrettier(String version) { + public static Map defaultDevDependenciesWithPrettier(String version) { return Collections.singletonMap("prettier", version); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java b/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java index 6956545135..8ba8a99d98 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java @@ -103,7 +103,7 @@ private static String guessPlugin(File file) { return EXTENSIONS_TO_PLUGINS.entrySet().stream() .filter(entry -> file.getName().endsWith(entry.getKey())) .findFirst() - .map(entry -> entry.getValue()) + .map(Map.Entry::getValue) .orElse("prettier-plugin-" + extension(file)); } 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 561839c757..d2af1ddad1 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/SimpleRestClient.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/SimpleRestClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,8 +72,7 @@ String postJson(String endpoint, @Nullable String rawJson) throws SimpleRestExce throw new SimpleRestResponseException(status, readError(con), "Unexpected response status code at " + endpoint); } - String response = readResponse(con); - return response; + return readResponse(con); } catch (IOException e) { throw new SimpleRestIOException(e); } diff --git a/lib/src/main/java/com/diffplug/spotless/pom/SortPomStep.java b/lib/src/main/java/com/diffplug/spotless/pom/SortPomStep.java index 69d833f8e7..e4469220ae 100644 --- a/lib/src/main/java/com/diffplug/spotless/pom/SortPomStep.java +++ b/lib/src/main/java/com/diffplug/spotless/pom/SortPomStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2021 DiffPlug + * Copyright 2021-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ public static FormatterStep create(SortPomCfg cfg, Provisioner provisioner) { static class State implements Serializable { private static final long serialVersionUID = 1; - SortPomCfg cfg; + final SortPomCfg cfg; JarState jarState; public State(SortPomCfg cfg, Provisioner provisioner) throws IOException { 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 f488bd5a00..d2e3d024f3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,9 +51,9 @@ public class DBeaverSQLFormatterConfiguration { */ private static final String SQL_FORMATTER_INDENT_SIZE = "sql.formatter.indent.size"; - private String statementDelimiters; - private KeywordCase keywordCase; - private String indentString; + private final String statementDelimiters; + private final KeywordCase keywordCase; + private final String indentString; public DBeaverSQLFormatterConfiguration(Properties properties) { this.keywordCase = KeywordCase.valueOf(properties.getProperty(SQL_FORMATTER_KEYWORD_CASE, "UPPER")); 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..bb29bee26c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,12 +64,10 @@ public int getPos() { } public String toString() { - final StringBuilder buf = new StringBuilder(); - buf.append(getClass().getName()); - buf.append("type=").append(fType); - buf.append(",string=").append(fString); - buf.append(",pos=").append(fPos); - buf.append("]"); - return buf.toString(); + return getClass().getName() + + "type=" + fType + + ",string=" + fString + + ",pos=" + fPos + + "]"; } } diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLDialect.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLDialect.java index 3c973885f6..d2a7918ca7 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLDialect.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLDialect.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,12 +39,12 @@ class SQLDialect { private static final String[][] DEFAULT_QUOTE_STRINGS = {{"\"", "\""}}; // Keywords - private TreeMap allKeywords = new TreeMap<>(); + private final TreeMap allKeywords = new TreeMap<>(); private final TreeSet functions = new TreeSet<>(); private final TreeSet types = new TreeSet<>(); // Comments - private Pair multiLineComments = new Pair<>(SQLConstants.ML_COMMENT_START, SQLConstants.ML_COMMENT_END); + private final Pair multiLineComments = new Pair<>(SQLConstants.ML_COMMENT_START, SQLConstants.ML_COMMENT_END); static final SQLDialect INSTANCE = new SQLDialect(); 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 f2c98eebc1..a78aaf2abc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,9 +38,9 @@ public class SQLTokenizedFormatter { private static final String[] JOIN_BEGIN = {"LEFT", "RIGHT", "INNER", "OUTER", "JOIN"}; private static final SQLDialect sqlDialect = SQLDialect.INSTANCE; - private DBeaverSQLFormatterConfiguration formatterCfg; - private List functionBracket = new ArrayList<>(); - private List statementDelimiters = new ArrayList<>(2); + private final DBeaverSQLFormatterConfiguration formatterCfg; + private final List functionBracket = new ArrayList<>(); + private final List statementDelimiters = new ArrayList<>(2); public SQLTokenizedFormatter(DBeaverSQLFormatterConfiguration formatterCfg) { this.formatterCfg = formatterCfg; @@ -53,10 +53,7 @@ public String format(final String argSql) { functionBracket.clear(); - boolean isSqlEndsWithNewLine = false; - if (argSql.endsWith("\n")) { - isSqlEndsWithNewLine = true; - } + boolean isSqlEndsWithNewLine = argSql.endsWith("\n"); List list = fParser.parse(argSql); list = format(list); diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java index 72080d22fc..4e9c022d3d 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,11 +37,11 @@ class SQLTokensParser { private final String[][] quoteStrings; private String fBefore = null; private int fPos; - private char structSeparator; - private String catalogSeparator; - private Set commands = new HashSet<>(); - private String[] singleLineComments; - private char[] singleLineCommentStart; + private final char structSeparator; + private final String catalogSeparator; + private final Set commands = new HashSet<>(); + private final String[] singleLineComments; + private final char[] singleLineCommentStart; SQLTokensParser() { this.structSeparator = sqlDialect.getStructSeparator(); @@ -185,7 +185,7 @@ else if (contains(singleLineCommentStart, fChar)) { s.append(fChar); } } - return new FormatterToken(TokenType.COMMAND, word + s.toString(), start_pos); + return new FormatterToken(TokenType.COMMAND, word + s, start_pos); } if (sqlDialect.getKeywordType(word) != null) { return new FormatterToken(TokenType.KEYWORD, word, start_pos); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/AJacksonGradleConfig.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/AJacksonGradleConfig.java index c017d41d04..9ed6edbb9e 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/AJacksonGradleConfig.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/AJacksonGradleConfig.java @@ -24,7 +24,7 @@ public abstract class AJacksonGradleConfig { protected final FormatExtension formatExtension; - protected JacksonConfig jacksonConfig; + protected final JacksonConfig jacksonConfig; protected String version = JacksonJsonStep.defaultVersion(); 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 fd613e82e1..9fab2a3a7d 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 @@ -120,7 +120,7 @@ public void setEncoding(String name) { /** @see #setRatchetFrom(String) */ public String getRatchetFrom() { - return ratchetFrom == RATCHETFROM_NOT_SET_AT_FORMAT_LEVEL ? spotless.getRatchetFrom() : ratchetFrom; + return RATCHETFROM_NOT_SET_AT_FORMAT_LEVEL.equals(ratchetFrom) ? spotless.getRatchetFrom() : ratchetFrom; } /** @@ -164,11 +164,7 @@ public void encoding(String charset) { protected boolean isLicenseHeaderStep(FormatterStep formatterStep) { String formatterStepName = formatterStep.getName(); - if (formatterStepName.startsWith(LicenseHeaderStep.class.getName())) { - return true; - } - - return false; + return formatterStepName.startsWith(LicenseHeaderStep.class.getName()); } /** @@ -227,9 +223,9 @@ protected final FileCollection parseTarget(Object target) { return parseTargetIsExclude(target, false); } - private final FileCollection parseTargetIsExclude(Object target, boolean isExclude) { + private FileCollection parseTargetIsExclude(Object target, boolean isExclude) { if (target instanceof Collection) { - return parseTargetsIsExclude(((Collection) target).toArray(), isExclude); + return parseTargetsIsExclude(((Collection) target).toArray(), isExclude); } else if (target instanceof FileCollection) { return (FileCollection) target; } else if (target instanceof String) { @@ -537,9 +533,9 @@ public abstract static class NpmStepConfig> { @Nullable protected Object npmrcFile; - protected Project project; + protected final Project project; - private Consumer replaceStep; + private final Consumer replaceStep; public NpmStepConfig(Project project, Consumer replaceStep) { this.project = requireNonNull(project); @@ -859,11 +855,10 @@ public TaskProvider createIndependentApplyTaskLazy(String taskNam task.mustRunAfter(BasePlugin.CLEAN_TASK_NAME); }); // create the apply task - TaskProvider applyTask = spotless.project.getTasks().register(taskName, SpotlessApply.class, task -> { + return spotless.project.getTasks().register(taskName, SpotlessApply.class, task -> { task.dependsOn(spotlessTask); task.init(spotlessTask.get()); }); - return applyTask; } protected GradleException noDefaultTargetException() { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GradleProvisioner.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GradleProvisioner.java index e1129b3b0b..c55b78a514 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GradleProvisioner.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GradleProvisioner.java @@ -120,9 +120,7 @@ private static Provisioner forConfigurationContainer(Project project, Configurat config.setTransitive(withTransitives); config.setCanBeConsumed(false); config.setVisible(false); - config.attributes(attr -> { - attr.attribute(Bundling.BUNDLING_ATTRIBUTE, project.getObjects().named(Bundling.class, Bundling.EXTERNAL)); - }); + config.attributes(attr -> attr.attribute(Bundling.BUNDLING_ATTRIBUTE, project.getObjects().named(Bundling.class, Bundling.EXTERNAL))); return config.resolve(); } catch (Exception e) { String projName = project.getPath().substring(1).replace(':', '/'); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java index bfe1a96955..4d52c5d4d4 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java @@ -282,9 +282,9 @@ public class CleanthatJavaConfig { private String sourceJdk = CleanthatJavaStep.defaultSourceJdk(); - private List mutators = new ArrayList<>(CleanthatJavaStep.defaultMutators()); + private final List mutators = new ArrayList<>(CleanthatJavaStep.defaultMutators()); - private List excludedMutators = new ArrayList<>(CleanthatJavaStep.defaultExcludedMutators()); + private final List excludedMutators = new ArrayList<>(CleanthatJavaStep.defaultExcludedMutators()); private boolean includeDraft = CleanthatJavaStep.defaultIncludeDraft(); 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 e8a76166bc..2a2e82e2a8 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 @@ -59,7 +59,7 @@ public JavascriptEslintConfig eslint(Map devDependencies) { } public static abstract class EslintBaseConfig> extends NpmStepConfig> { - Map devDependencies = new LinkedHashMap<>(); + final Map devDependencies = new LinkedHashMap<>(); @Nullable Object configFilePath = null; 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 39b158ce1e..9771525386 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 @@ -117,7 +117,7 @@ private FormatterStep createStep() { } public static class JacksonJsonGradleConfig extends AJacksonGradleConfig { - protected JacksonJsonConfig jacksonConfig; + protected final JacksonJsonConfig jacksonConfig; public JacksonJsonGradleConfig(JacksonJsonConfig jacksonConfig, FormatExtension formatExtension) { super(jacksonConfig, formatExtension); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JvmLocalCache.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JvmLocalCache.java index bcc480b7c6..e396b45be1 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JvmLocalCache.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JvmLocalCache.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2022 DiffPlug + * Copyright 2021-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,11 +42,11 @@ interface LiveCache { } static LiveCache createLive(Task task, String propertyName) { - return new LiveCacheKeyImpl(new InternalCacheKey(task.getProject().getProjectDir(), task.getPath(), propertyName)); + return new LiveCacheKeyImpl<>(new InternalCacheKey(task.getProject().getProjectDir(), task.getPath(), propertyName)); } static class LiveCacheKeyImpl implements LiveCache, Serializable { - InternalCacheKey internalKey; + final InternalCacheKey internalKey; LiveCacheKeyImpl(InternalCacheKey internalKey) { this.internalKey = internalKey; @@ -73,12 +73,12 @@ public T get() { } } - private static Map daemonState = Collections.synchronizedMap(new HashMap<>()); + private static final Map daemonState = Collections.synchronizedMap(new HashMap<>()); private static class InternalCacheKey implements Serializable { - private File projectDir; - private String taskPath; - private String propertyName; + private final File projectDir; + private final String taskPath; + private final String propertyName; InternalCacheKey(File projectDir, String taskPath, String keyName) { this.projectDir = projectDir; diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java index 75bd06406b..f61a16661b 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ void setup() { unitOutput = new File(getProject().getBuildDir(), "tmp/spotless-register-dependencies"); } - List steps = new ArrayList<>(); + final List steps = new ArrayList<>(); @Input public List getSteps() { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionImpl.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionImpl.java index 96474ffc4b..f9ae33bd1d 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionImpl.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,16 +60,14 @@ protected void createFormatTasks(String name, FormatExtension formatExtension) { // clean removes the SpotlessCache, so we have to run after clean task.mustRunAfter(BasePlugin.CLEAN_TASK_NAME); }); - project.afterEvaluate(unused -> { - spotlessTask.configure(task -> { - // now that the task is being configured, we execute our actions - for (Action lazyAction : formatExtension.lazyActions) { - lazyAction.execute(formatExtension); - } - // and now we'll setup the task - formatExtension.setupTask(task); - }); - }); + project.afterEvaluate(unused -> spotlessTask.configure(task -> { + // now that the task is being configured, we execute our actions + for (Action lazyAction : formatExtension.lazyActions) { + lazyAction.execute(formatExtension); + } + // and now we'll setup the task + formatExtension.setupTask(task); + })); // create the check and apply control tasks TaskProvider applyTask = tasks.register(taskName + APPLY, SpotlessApply.class, task -> { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionPredeclare.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionPredeclare.java index ae6243f53a..fadda9b9fe 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionPredeclare.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionPredeclare.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2022 DiffPlug + * Copyright 2021-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,16 +29,14 @@ public class SpotlessExtensionPredeclare extends SpotlessExtension { public SpotlessExtensionPredeclare(Project project, GradleProvisioner.Policy policy) { super(project); getRegisterDependenciesTask().getTaskService().get().predeclaredProvisioner = policy.dedupingProvisioner(project); - project.afterEvaluate(unused -> { - toSetup.forEach((name, formatExtension) -> { - for (Action lazyAction : formatExtension.lazyActions) { - lazyAction.execute(formatExtension); - } - getRegisterDependenciesTask().steps.addAll(formatExtension.steps); - // needed to fix Deemon memory leaks (#1194), but this line came from https://github.com/diffplug/spotless/pull/1206 - LazyForwardingEquality.unlazy(getRegisterDependenciesTask().steps); - }); - }); + project.afterEvaluate(unused -> toSetup.forEach((name, formatExtension) -> { + for (Action lazyAction : formatExtension.lazyActions) { + lazyAction.execute(formatExtension); + } + getRegisterDependenciesTask().steps.addAll(formatExtension.steps); + // needed to fix Deemon memory leaks (#1194), but this line came from https://github.com/diffplug/spotless/pull/1206 + LazyForwardingEquality.unlazy(getRegisterDependenciesTask().steps); + })); } @Override diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessPluginRedirect.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessPluginRedirect.java index da4d3dcd8b..10fb77b070 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessPluginRedirect.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessPluginRedirect.java @@ -1,5 +1,5 @@ /* - * Copyright 2020 DiffPlug + * Copyright 2020-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ static boolean gradleIsTooOld(Project project) { if (gradleIsTooOld == null) { gradleIsTooOld = badSemver(project.getGradle().getGradleVersion()) < badSemver(SpotlessPlugin.MINIMUM_GRADLE); } - return gradleIsTooOld.booleanValue(); + return gradleIsTooOld; } @Override diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java index c23cea0845..c00446bc3f 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java @@ -89,7 +89,7 @@ public void setLineEndingsPolicy(LineEnding.Policy lineEndingsPolicy) { public void setupRatchet(String ratchetFrom) { this.ratchetFrom = ratchetFrom; if (!ratchetFrom.isEmpty()) { - GitRatchet ratchet = getTaskService().get().getRatchet(); + GitRatchet ratchet = getTaskService().get().getRatchet(); File projectDir = getProjectDir().get().getAsFile(); rootTreeSha = ratchet.rootTreeShaOf(projectDir, ratchetFrom); subtreeSha = ratchet.subtreeShaOf(projectDir, rootTreeSha); @@ -147,7 +147,7 @@ public void setTarget(Iterable target) { } } - protected File outputDirectory = new File(getProject().getBuildDir(), "spotless/" + getName()); + protected final File outputDirectory = new File(getProject().getBuildDir(), "spotless/" + getName()); @OutputDirectory public File getOutputDirectory() { @@ -156,7 +156,7 @@ public File getOutputDirectory() { protected final LiveCache> steps = createLive("steps"); { - steps.set(new ArrayList()); + steps.set(new ArrayList<>()); } @Input 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 ab584fa7b6..1048ee9768 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 @@ -94,7 +94,7 @@ public void performAction(InputChanges inputs) throws Exception { } @VisibleForTesting - void processInputFile(@Nullable GitRatchet ratchet, Formatter formatter, File input) throws IOException { + void processInputFile(@Nullable GitRatchet ratchet, Formatter formatter, File input) throws IOException { File output = getOutputFile(input); getLogger().debug("Applying format to {} and writing to {}", input, output); PaddedCell.DirtyState dirtyState; 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 67de4b946c..b04918dbf4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2021-2022 DiffPlug + * Copyright 2021-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,7 +89,7 @@ public void close() throws Exception { } // - static String INDEPENDENT_HELPER = "Helper"; + static final String INDEPENDENT_HELPER = "Helper"; static abstract class ClientTask extends DefaultTask { @Internal diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/YamlExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/YamlExtension.java index abc2dce359..c498c2fe64 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/YamlExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/YamlExtension.java @@ -44,7 +44,7 @@ public AJacksonGradleConfig jackson() { } public class JacksonYamlGradleConfig extends AJacksonGradleConfig { - protected JacksonYamlConfig jacksonConfig; + protected final JacksonYamlConfig jacksonConfig; public JacksonYamlGradleConfig(JacksonYamlConfig jacksonConfig, FormatExtension formatExtension) { super(jacksonConfig, formatExtension); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java index ef72043a47..4041e2093f 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,17 +40,17 @@ class DiffMessageFormatterTest extends ResourceHarness { private class Bundle { - Project project = TestProvisioner.gradleProject(rootFolder()); - Provider taskService = GradleIntegrationHarness.providerOf(new SpotlessTaskService() { + final Project project = TestProvisioner.gradleProject(rootFolder()); + final Provider taskService = GradleIntegrationHarness.providerOf(new SpotlessTaskService() { @Override public BuildServiceParameters.None getParameters() { return null; } }); - File file; - SpotlessTaskImpl task; - SpotlessCheck check; + final File file; + final SpotlessTaskImpl task; + final SpotlessCheck check; Bundle(String name) throws IOException { file = setFile("src/test." + name).toContent("CCC"); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GitRatchetGradleTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GitRatchetGradleTest.java index 51f4808259..a4376358b2 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GitRatchetGradleTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GitRatchetGradleTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -248,7 +248,7 @@ void multiProject(int useConfigCache) throws Exception { } public static class BuildResultAssertion { - BuildResult result; + final BuildResult result; BuildResultAssertion(BuildResult result) { this.result = Objects.requireNonNull(result); @@ -266,10 +266,9 @@ public BuildResultAssertion outcome(String taskPath, TaskOutcome expected) { private RevCommit addAndCommit(Git git) throws NoFilepatternException, GitAPIException { PersonIdent emptyPerson = new PersonIdent("jane doe", "jane@doe.com", new Date(0), TimeZone.getTimeZone("UTC")); git.add().addFilepattern(".").call(); - RevCommit commit = git.commit().setMessage("baseline") + return git.commit().setMessage("baseline") .setCommitter(emptyPerson) .setAuthor(emptyPerson) .call(); - return commit; } } 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..cc999aa268 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIncrementalResolutionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIncrementalResolutionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -97,7 +97,7 @@ private String filename(String name) { private void writeState(String state) throws IOException { for (char c : state.toCharArray()) { - String letter = new String(new char[]{c}); + String letter = String.valueOf(c); boolean exists = new File(rootFolder(), filename(letter)).exists(); boolean needsChanging = exists && !read(filename(letter)).trim().equals(letter); if (!exists || needsChanging) { @@ -108,7 +108,7 @@ private void writeState(String state) throws IOException { private void assertState(String state) throws IOException { for (char c : state.toCharArray()) { - String letter = new String(new char[]{c}); + String letter = String.valueOf(c); if (Character.isLowerCase(c)) { assertEquals(letter.toLowerCase(Locale.ROOT), read(filename(letter)).trim()); } 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 1763fd088f..aa95799da5 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 @@ -135,9 +135,7 @@ protected String getContents(Predicate subpathsToInclude) { /** Dumps the filtered file listing of the folder to the console. */ protected String listFiles(Predicate subpathsToInclude) { - return StringPrinter.buildString(printer -> iterateFiles(subpathsToInclude, (subPath, file) -> { - printer.println(subPath + " [" + getFileAttributes(file) + "]"); - })); + return StringPrinter.buildString(printer -> iterateFiles(subpathsToInclude, (subPath, file) -> printer.println(subPath + " [" + getFileAttributes(file) + "]"))); } /** Dumps the file listing of the folder to the console. */ diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IdeHookTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IdeHookTest.java index f28b9f9820..7062c155fe 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IdeHookTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IdeHookTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ private void runWith(String... arguments) throws IOException { StringBuilder output = new StringBuilder(); StringBuilder error = new StringBuilder(); try (Writer outputWriter = new StringPrinter(output::append).toWriter(); - Writer errorWriter = new StringPrinter(error::append).toWriter();) { + Writer errorWriter = new StringPrinter(error::append).toWriter()) { gradleRunner() .withArguments(arguments) .forwardStdOutput(outputWriter) diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/MultiProjectTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/MultiProjectTest.java index 086a2ddb1d..be65a89ca5 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/MultiProjectTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/MultiProjectTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import com.diffplug.common.base.StringPrinter; class MultiProjectTest extends GradleIntegrationHarness { - private static int N = 100; + private static final int N = 100; private void createNSubprojects() throws IOException { for (int i = 0; i < N; ++i) { diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/NpmInstallCacheIntegrationTests.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/NpmInstallCacheIntegrationTests.java index 3a690fbc55..7de09567d6 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/NpmInstallCacheIntegrationTests.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/NpmInstallCacheIntegrationTests.java @@ -49,8 +49,7 @@ static void beforeAll(@TempDir File pertainingCacheDir) { @Test void prettierCachesNodeModulesToADefaultFolderWhenCachingEnabled() throws IOException { File dir1 = newFolder("npm-prettier-1"); - File cacheDir = DEFAULT_DIR_FOR_NPM_INSTALL_CACHE_DO_NEVER_WRITE_TO_THIS; - BuildResult result = runPhpPrettierOnDir(dir1, cacheDir); + BuildResult result = runPhpPrettierOnDir(dir1, DEFAULT_DIR_FOR_NPM_INSTALL_CACHE_DO_NEVER_WRITE_TO_THIS); Assertions.assertThat(result.getOutput()) .doesNotContain("Using cached node_modules for") .contains("Caching node_modules for ") diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PaddedCellTaskTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PaddedCellTaskTest.java index bc7a2fdc96..b76866d6e0 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PaddedCellTaskTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PaddedCellTaskTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,19 +38,19 @@ class PaddedCellTaskTest extends ResourceHarness { private class Bundle { - String name; - Project project = TestProvisioner.gradleProject(rootFolder()); - Provider taskService = GradleIntegrationHarness.providerOf(new SpotlessTaskService() { + final String name; + final Project project = TestProvisioner.gradleProject(rootFolder()); + final Provider taskService = GradleIntegrationHarness.providerOf(new SpotlessTaskService() { @Override public BuildServiceParameters.None getParameters() { return null; } }); - File file; - File outputFile; - SpotlessTaskImpl source; - SpotlessCheck check; - SpotlessApply apply; + final File file; + final File outputFile; + final SpotlessTaskImpl source; + final SpotlessCheck check; + final SpotlessApply apply; Bundle(String name, FormatterFunc function) throws IOException { this.name = name; 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..452bf4d2d4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,12 +61,12 @@ public ArtifactResolver(RepositorySystem repositorySystem, RepositorySystemSessi * of the specified coordinates and optionally their transitive dependencies. */ public Set resolve(boolean withTransitives, Collection mavenCoordinates) { - Collection excludeTransitive = new ArrayList(1); + Collection excludeTransitive = new ArrayList<>(1); if (!withTransitives) { excludeTransitive.add(EXCLUDE_ALL_TRANSITIVES); } List dependencies = mavenCoordinates.stream() - .map(coordinateString -> new DefaultArtifact(coordinateString)) + .map(DefaultArtifact::new) .map(artifact -> new Dependency(artifact, null, null, excludeTransitive)) .collect(toList()); CollectRequest collectRequest = new CollectRequest(dependencies, null, repositories); diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java index c4a6663087..6e34ef77a8 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java @@ -95,7 +95,7 @@ public final Formatter newFormatter(Supplier> filesToFormat, Form List formatterSteps = factories.stream() .filter(Objects::nonNull) // all unrecognized steps from XML config appear as nulls in the list .map(factory -> factory.newFormatterStep(stepConfig)) - .collect(Collectors.toCollection(() -> new ArrayList())); + .collect(Collectors.toCollection(ArrayList::new)); if (toggle != null) { PipeStepPair pair = toggle.createPair(); formatterSteps.add(0, pair.in()); 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 78484abfba..678ee2e814 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package com.diffplug.spotless.maven.cpp; import java.io.File; -import java.util.Arrays; +import java.util.Collections; import org.apache.maven.plugins.annotations.Parameter; @@ -40,7 +40,7 @@ public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) { eclipseConfig.setVersion(version == null ? EclipseCdtFormatterStep.defaultVersion() : version); if (null != file) { File settingsFile = stepConfig.getFileLocator().locateFile(file); - eclipseConfig.setPreferences(Arrays.asList(settingsFile)); + eclipseConfig.setPreferences(Collections.singletonList(settingsFile)); } return eclipseConfig.build(); } 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 81da109e04..107fe9b9ce 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 @@ -1,5 +1,5 @@ /* - * Copyright 2020 DiffPlug + * Copyright 2020-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package com.diffplug.spotless.maven.groovy; import java.io.File; -import java.util.Arrays; +import java.util.Collections; import org.apache.maven.plugins.annotations.Parameter; @@ -40,7 +40,7 @@ public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) { grEclipseConfig.setVersion(version == null ? GrEclipseFormatterStep.defaultVersion() : version); if (null != file) { File settingsFile = stepConfig.getFileLocator().locateFile(file); - grEclipseConfig.setPreferences(Arrays.asList(settingsFile)); + grEclipseConfig.setPreferences(Collections.singletonList(settingsFile)); } return grEclipseConfig.build(); } 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 1e6508121e..f7e523f3c7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package com.diffplug.spotless.maven.java; import java.io.File; -import java.util.Arrays; +import java.util.Collections; import org.apache.maven.plugins.annotations.Parameter; @@ -40,7 +40,7 @@ public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) { eclipseConfig.setVersion(version == null ? EclipseJdtFormatterStep.defaultVersion() : version); if (null != file) { File settingsFile = stepConfig.getFileLocator().locateFile(file); - eclipseConfig.setPreferences(Arrays.asList(settingsFile)); + eclipseConfig.setPreferences(Collections.singletonList(settingsFile)); } return eclipseConfig.build(); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java index b0645c151e..c5115952a2 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java @@ -49,18 +49,15 @@ public abstract class AbstractNpmFormatterStepFactory implements FormatterStepFa private String npmInstallCache; protected File npm(FormatterStepConfig stepConfig) { - File npm = npmExecutable != null ? stepConfig.getFileLocator().locateFile(npmExecutable) : null; - return npm; + return npmExecutable != null ? stepConfig.getFileLocator().locateFile(npmExecutable) : null; } protected File node(FormatterStepConfig stepConfig) { - File node = nodeExecutable != null ? stepConfig.getFileLocator().locateFile(nodeExecutable) : null; - return node; + return nodeExecutable != null ? stepConfig.getFileLocator().locateFile(nodeExecutable) : null; } protected File npmrc(FormatterStepConfig stepConfig) { - File npmrc = this.npmrc != null ? stepConfig.getFileLocator().locateFile(this.npmrc) : null; - return npmrc; + return this.npmrc != null ? stepConfig.getFileLocator().locateFile(this.npmrc) : null; } protected File buildDir(FormatterStepConfig stepConfig) { diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java index d878b18c5f..1b32ac9a5e 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java @@ -40,7 +40,7 @@ private MavenRunner() {} private File projectDir; private String[] args; - private Map environment = new HashMap<>(); + private final Map environment = new HashMap<>(); private ProcessRunner runner; public MavenRunner withProjectDir(File projectDir) { diff --git a/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java b/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java index 4d0a340f42..d7555a8730 100644 --- a/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java +++ b/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ public static void dumpAllInfo(String name, Object obj) { public static void dumpMethod(Method method) { System.out.print(Modifier.toString(method.getModifiers())); - System.out.print(" " + method.getReturnType().toString()); + System.out.print(" " + method.getReturnType()); System.out.print(" " + method.getName() + "("); Iterator paramIter = Arrays.asList(method.getParameters()).iterator(); while (paramIter.hasNext()) { diff --git a/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java b/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java index 0304889e1f..7cb3b61882 100644 --- a/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java +++ b/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java @@ -174,7 +174,7 @@ protected WriteAsserter setFile(String path) { } public static class WriteAsserter { - private File file; + private final File file; private WriteAsserter(File file) { file.getParentFile().mkdirs(); @@ -190,16 +190,12 @@ public File toContent(String content) { } public File toContent(String content, Charset charset) { - ThrowingEx.run(() -> { - Files.write(file.toPath(), content.getBytes(charset)); - }); + ThrowingEx.run(() -> Files.write(file.toPath(), content.getBytes(charset))); return file; } public File toResource(String path) { - ThrowingEx.run(() -> { - Files.write(file.toPath(), getTestResource(path).getBytes(StandardCharsets.UTF_8)); - }); + ThrowingEx.run(() -> Files.write(file.toPath(), getTestResource(path).getBytes(StandardCharsets.UTF_8))); return file; } diff --git a/testlib/src/main/java/com/diffplug/spotless/SerializableEqualityTester.java b/testlib/src/main/java/com/diffplug/spotless/SerializableEqualityTester.java index 096edf62e2..e574300f7e 100644 --- a/testlib/src/main/java/com/diffplug/spotless/SerializableEqualityTester.java +++ b/testlib/src/main/java/com/diffplug/spotless/SerializableEqualityTester.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,23 +37,18 @@ public interface API { public void testEquals() { List> allGroups = new ArrayList<>(); Box> currentGroup = Box.of(new ArrayList<>()); - API api = new API() { - @Override - public void areDifferentThan() { - currentGroup.modify(current -> { - // create two instances, and add them to the group - current.add(create()); - current.add(create()); - // create two instances using a serialization roundtrip, and add them to the group - current.add(reserialize(create())); - current.add(reserialize(create())); - // add this group to the list of all groups - allGroups.add(current); - // and return a new blank group for the next call - return new ArrayList<>(); - }); - } - }; + API api = () -> currentGroup.modify(current -> { + // create two instances, and add them to the group + current.add(create()); + current.add(create()); + // create two instances using a serialization roundtrip, and add them to the group + current.add(reserialize(create())); + current.add(reserialize(create())); + // add this group to the list of all groups + allGroups.add(current); + // and return a new blank group for the next call + return new ArrayList<>(); + }); try { setupTest(api); } catch (Exception e) { diff --git a/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java b/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java index 0d9ced4c9e..9094ea4a97 100644 --- a/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java +++ b/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,9 +69,7 @@ private static Provisioner createWithRepositories(Consumer re Configuration config = project.getConfigurations().detachedConfiguration(deps); config.setTransitive(withTransitives); config.setDescription(mavenCoords.toString()); - config.attributes(attr -> { - attr.attribute(Bundling.BUNDLING_ATTRIBUTE, project.getObjects().named(Bundling.class, Bundling.EXTERNAL)); - }); + config.attributes(attr -> attr.attribute(Bundling.BUNDLING_ATTRIBUTE, project.getObjects().named(Bundling.class, Bundling.EXTERNAL))); try { return config.resolve(); } catch (ResolveException e) { @@ -138,25 +136,19 @@ public static Provisioner mavenCentral() { return mavenCentral.get(); } - private static final Supplier mavenCentral = Suppliers.memoize(() -> { - return caching("mavenCentral", () -> createWithRepositories(repo -> repo.mavenCentral())); - }); + private static final Supplier mavenCentral = Suppliers.memoize(() -> caching("mavenCentral", () -> createWithRepositories(RepositoryHandler::mavenCentral))); /** Creates a Provisioner for the local maven repo for development purpose. */ public static Provisioner mavenLocal() { return mavenLocal.get(); } - private static final Supplier mavenLocal = () -> createWithRepositories(repo -> repo.mavenLocal()); + private static final Supplier mavenLocal = () -> createWithRepositories(RepositoryHandler::mavenLocal); /** Creates a Provisioner for the Sonatype snapshots maven repo for development purpose. */ public static Provisioner snapshots() { return snapshots.get(); } - private static final Supplier snapshots = () -> createWithRepositories(repo -> { - repo.maven(setup -> { - setup.setUrl("https://oss.sonatype.org/content/repositories/snapshots"); - }); - }); + private static final Supplier snapshots = () -> createWithRepositories(repo -> repo.maven(setup -> setup.setUrl("https://oss.sonatype.org/content/repositories/snapshots"))); } diff --git a/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java b/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java index d634119567..5457f47873 100644 --- a/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,7 +90,7 @@ private void utf8asCP1252(String test, @Nullable String expectedMessage) throws @Test void canUseUnrepresentableOnPurpose() throws UnsupportedEncodingException { - String pathologic = new String(new char[]{EncodingErrorMsg.UNREPRESENTABLE}); + String pathologic = String.valueOf(EncodingErrorMsg.UNREPRESENTABLE); byte[] pathologicBytes = pathologic.getBytes(StandardCharsets.UTF_8); String pathologicMsg = EncodingErrorMsg.msg(pathologic, pathologicBytes, StandardCharsets.UTF_8); Assertions.assertThat(pathologicMsg).isNull(); diff --git a/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java b/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java index 5e47e9ad1a..0f99654593 100644 --- a/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -116,7 +116,7 @@ public FormatterSettingsAssert(FormatterProperties actual) { /** Check that the values form all valid files are part of the settings properties. */ public FormatterSettingsAssert containsSpecificValuesOf(Collection files) { - files.forEach(file -> containsSpecificValuesOf(file)); + files.forEach(this::containsSpecificValuesOf); return this; } diff --git a/testlib/src/test/java/com/diffplug/spotless/FormatterTest.java b/testlib/src/test/java/com/diffplug/spotless/FormatterTest.java index 314507bd8d..5ac8c9af75 100644 --- a/testlib/src/test/java/com/diffplug/spotless/FormatterTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/FormatterTest.java @@ -48,7 +48,7 @@ void equality() { private LineEnding.Policy lineEndingsPolicy = LineEnding.UNIX.createPolicy(); private Charset encoding = StandardCharsets.UTF_8; private Path rootDir = Paths.get(StandardSystemProperty.USER_DIR.value()); - private List steps = new ArrayList<>(); + private final List steps = new ArrayList<>(); private FormatExceptionPolicy exceptionPolicy = FormatExceptionPolicy.failOnlyOnError(); @Override diff --git a/testlib/src/test/java/com/diffplug/spotless/JvmTest.java b/testlib/src/test/java/com/diffplug/spotless/JvmTest.java index ca7fb71305..08b2d6ce56 100644 --- a/testlib/src/test/java/com/diffplug/spotless/JvmTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/JvmTest.java @@ -42,18 +42,16 @@ 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))); + Integer[] differentVersions = {0, 1, 2}; + Arrays.stream(differentVersions).forEach(v -> testSupport.add(v + Jvm.version(), v.toString())); + Arrays.stream(differentVersions).forEach(v -> assertThat(testSupport.toString()).contains(String.format("Version %d", v))); assertThat(testSupport.toString()).contains(String.format("%s alternatives", TEST_NAME)); } @ParameterizedTest(name = "{index} {1}") @MethodSource void supportAddFailsFor(Consumer> configuration, String nameNotUsed) { - assertThrows(IllegalArgumentException.class, () -> { - configuration.accept(testSupport); - }); + assertThrows(IllegalArgumentException.class, () -> configuration.accept(testSupport)); } private static Stream supportAddFailsFor() { @@ -76,11 +74,9 @@ void supportEmptyConfiguration() { testSupport.assertFormatterSupported("0.1"); Exception expected = new Exception("Some test exception"); - Exception actual = assertThrows(Exception.class, () -> { - testSupport.suggestLaterVersionOnError("0.0", unused -> { - throw expected; - }).apply(""); - }); + Exception actual = assertThrows(Exception.class, () -> testSupport.suggestLaterVersionOnError("0.0", unused -> { + throw expected; + }).apply("")); assertEquals(expected, actual); } @@ -94,34 +90,26 @@ void supportListsMinimumJvmIfOnlyHigherJvmSupported() { assertNull(testSupport.getRecommendedFormatterVersion(), "No formatter version is supported"); for (String fmtVersion : Arrays.asList("1.2", "1.2.3")) { - String proposal = assertThrows(Exception.class, () -> { - testSupport.assertFormatterSupported(fmtVersion); - }).getMessage(); + String proposal = assertThrows(Exception.class, () -> testSupport.assertFormatterSupported(fmtVersion)).getMessage(); assertThat(proposal).contains(String.format("on JVM %d", Jvm.version())); assertThat(proposal).contains(String.format("%s %s requires JVM %d+", TEST_NAME, fmtVersion, higherJvmVersion)); assertThat(proposal).contains(String.format("try %s alternatives", TEST_NAME)); - proposal = assertThrows(Exception.class, () -> { - testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { - throw testException; - }).apply(""); - }).getMessage(); + proposal = assertThrows(Exception.class, () -> testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { + throw testException; + }).apply("")).getMessage(); assertThat(proposal).contains(String.format("on JVM %d", Jvm.version())); assertThat(proposal).contains(String.format("%s %s requires JVM %d+", TEST_NAME, fmtVersion, higherJvmVersion)); assertThat(proposal).contains(String.format("try %s alternatives", TEST_NAME)); } for (String fmtVersion : Arrays.asList("1.2.4", "2")) { - String proposal = assertThrows(Exception.class, () -> { - testSupport.assertFormatterSupported(fmtVersion); - }).getMessage(); + String proposal = assertThrows(Exception.class, () -> testSupport.assertFormatterSupported(fmtVersion)).getMessage(); assertThat(proposal).contains(String.format("%s %s requires JVM %d+", TEST_NAME, fmtVersion, higherJvmVersion + 1)); - proposal = assertThrows(Exception.class, () -> { - testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { - throw testException; - }).apply(""); - }).getMessage(); + proposal = assertThrows(Exception.class, () -> testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { + throw testException; + }).apply("")).getMessage(); assertThat(proposal).contains(String.format("%s %s requires JVM %d+", TEST_NAME, fmtVersion, higherJvmVersion + 1)); } } @@ -135,11 +123,9 @@ void supportProposesFormatterUpgrade() { for (String fmtVersion : Arrays.asList("0", "1", "1.9")) { testSupport.assertFormatterSupported(fmtVersion); - String proposal = assertThrows(Exception.class, () -> { - testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { - throw new Exception("Some test exception"); - }).apply(""); - }).getMessage(); + String proposal = assertThrows(Exception.class, () -> testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { + throw new Exception("Some test exception"); + }).apply("")).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) + "+."); @@ -153,11 +139,9 @@ void supportProposesJvmUpgrade() { testSupport.add(higherJvm, "2"); testSupport.add(higherJvm + 1, "3"); for (String fmtVersion : Arrays.asList("1", "1.0")) { - String proposal = assertThrows(Exception.class, () -> { - testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { - throw new Exception("Some test exception"); - }).apply(""); - }).getMessage(); + String proposal = assertThrows(Exception.class, () -> testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { + throw new Exception("Some test exception"); + }).apply("")).getMessage(); assertThat(proposal).contains(String.format("on JVM %d", Jvm.version())); assertThat(proposal).contains(String.format("limits you to %s %s", TEST_NAME, "1")); assertThat(proposal).contains(String.format("upgrade your JVM to %d+", higherJvm)); @@ -172,11 +156,9 @@ void supportAllowsExperimentalVersions() { testSupport.assertFormatterSupported(fmtVersion); Exception testException = new Exception("Some test exception"); - Exception exception = assertThrows(Exception.class, () -> { - testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { - throw testException; - }).apply(""); - }); + Exception exception = assertThrows(Exception.class, () -> testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { + throw testException; + }).apply("")); assertEquals(testException, exception); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/LazyForwardingEqualityTest.java b/testlib/src/test/java/com/diffplug/spotless/LazyForwardingEqualityTest.java index d15eeb2773..f149f00b53 100644 --- a/testlib/src/test/java/com/diffplug/spotless/LazyForwardingEqualityTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/LazyForwardingEqualityTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ static Other o(String state) { } static class Str extends LazyForwardingEquality { - private String state; + private final String state; Str(String state) { this.state = state; diff --git a/testlib/src/test/java/com/diffplug/spotless/generic/PipeStepPairTest.java b/testlib/src/test/java/com/diffplug/spotless/generic/PipeStepPairTest.java index b648432b92..4f75c54355 100644 --- a/testlib/src/test/java/com/diffplug/spotless/generic/PipeStepPairTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/generic/PipeStepPairTest.java @@ -16,7 +16,7 @@ package com.diffplug.spotless.generic; import java.nio.file.Paths; -import java.util.Arrays; +import java.util.List; import java.util.Locale; import org.junit.jupiter.api.Test; @@ -98,7 +98,7 @@ void broken() { void andApply() { FormatterStep lowercase = FormatterStep.createNeverUpToDate("lowercase", str -> str.toLowerCase(Locale.ROOT)); FormatterStep lowercaseSometimes = PipeStepPair.named("lowercaseSometimes").openClose("", "") - .buildStepWhichAppliesSubSteps(Paths.get(""), Arrays.asList(lowercase)); + .buildStepWhichAppliesSubSteps(Paths.get(""), List.of(lowercase)); StepHarness.forSteps(lowercaseSometimes).test( StringPrinter.buildStringFromLines( "A B C", diff --git a/testlib/src/test/java/com/diffplug/spotless/java/FormatAnnotationsStepTest.java b/testlib/src/test/java/com/diffplug/spotless/java/FormatAnnotationsStepTest.java index 7aa0b64c00..693d6d2d68 100644 --- a/testlib/src/test/java/com/diffplug/spotless/java/FormatAnnotationsStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/java/FormatAnnotationsStepTest.java @@ -16,6 +16,7 @@ package com.diffplug.spotless.java; import java.util.Arrays; +import java.util.List; import org.junit.jupiter.api.Test; @@ -38,7 +39,7 @@ void formatAnnotationsInComments() { @Test void formatAnnotationsAddRemove() { - FormatterStep step = FormatAnnotationsStep.create(Arrays.asList("Empty", "NonEmpty"), Arrays.asList("Localized")); + FormatterStep step = FormatAnnotationsStep.create(Arrays.asList("Empty", "NonEmpty"), List.of("Localized")); StepHarness.forStep(step).testResource("java/formatannotations/FormatAnnotationsAddRemoveInput.test", "java/formatannotations/FormatAnnotationsAddRemoveOutput.test"); } diff --git a/testlib/src/test/java/com/diffplug/spotless/java/GoogleJavaFormatStepTest.java b/testlib/src/test/java/com/diffplug/spotless/java/GoogleJavaFormatStepTest.java index ff64b574e1..3ad86d055e 100644 --- a/testlib/src/test/java/com/diffplug/spotless/java/GoogleJavaFormatStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/java/GoogleJavaFormatStepTest.java @@ -127,9 +127,9 @@ protected FormatterStep create() { void equalityGroupArtifact() throws Exception { new SerializableEqualityTester() { String groupArtifact = GoogleJavaFormatStep.defaultGroupArtifact(); - String version = "1.11.0"; - String style = ""; - boolean reflowLongStrings = false; + final String version = "1.11.0"; + final String style = ""; + final boolean reflowLongStrings = false; @Override protected void setupTest(API api) { diff --git a/testlib/src/test/java/com/diffplug/spotless/markdown/FreshMarkStepTest.java b/testlib/src/test/java/com/diffplug/spotless/markdown/FreshMarkStepTest.java index 586212383d..fe1781b687 100644 --- a/testlib/src/test/java/com/diffplug/spotless/markdown/FreshMarkStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/markdown/FreshMarkStepTest.java @@ -39,7 +39,7 @@ void behavior() throws Exception { void equality() throws Exception { new SerializableEqualityTester() { String version = "1.3.1"; - Map props = new HashMap<>(); + final Map props = new HashMap<>(); @Override protected void setupTest(API api) { diff --git a/testlib/src/test/java/com/diffplug/spotless/npm/SimpleJsonWriterTest.java b/testlib/src/test/java/com/diffplug/spotless/npm/SimpleJsonWriterTest.java index 34d7966709..da5b564176 100644 --- a/testlib/src/test/java/com/diffplug/spotless/npm/SimpleJsonWriterTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/npm/SimpleJsonWriterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ class SimpleJsonWriterTest extends ResourceHarness { - private SimpleJsonWriter jsonWriter = new SimpleJsonWriter(); + private final SimpleJsonWriter jsonWriter = new SimpleJsonWriter(); @Test void itWritesAValidEmptyObject() { diff --git a/testlib/src/test/java/com/diffplug/spotless/scala/ScalaFmtStepTest.java b/testlib/src/test/java/com/diffplug/spotless/scala/ScalaFmtStepTest.java index c28046e148..dd02d35ca5 100644 --- a/testlib/src/test/java/com/diffplug/spotless/scala/ScalaFmtStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/scala/ScalaFmtStepTest.java @@ -86,8 +86,7 @@ protected FormatterStep create() { void invalidConfiguration() { File invalidConfFile = createTestFile("scala/scalafmt/scalafmt.invalid.conf"); Provisioner provisioner = TestProvisioner.mavenCentral(); - Assertions.assertThatThrownBy(() -> { - ScalaFmtStep.create("3.0.0", provisioner, invalidConfFile).format("", new File("")); - }).cause().message().contains("found option 'invalidScalaFmtConfigField' which wasn't expected"); + Assertions.assertThatThrownBy(() -> ScalaFmtStep.create("3.0.0", provisioner, invalidConfFile).format("", new File(""))) + .cause().message().contains("found option 'invalidScalaFmtConfigField' which wasn't expected"); } }