From df40c23fccddb6d4f44c58d125b9ffea4f5224e4 Mon Sep 17 00:00:00 2001 From: Vincent Potucek Date: Sat, 11 Oct 2025 20:42:25 +0200 Subject: [PATCH 1/3] Add `error-prone.picnic.tech` featuring `RedundantStringConversion` --- build.gradle | 1 + gradle/error-prone.gradle | 30 +++++++++++++++++++ .../com/diffplug/spotless/ForeignExe.java | 2 +- .../biome/BiomeExecutableDownloader.java | 2 +- .../spotless/sql/dbeaver/SQLTokensParser.java | 2 +- settings.gradle | 1 + .../com/diffplug/spotless/ReflectionUtil.java | 2 +- 7 files changed, 36 insertions(+), 4 deletions(-) create mode 100644 gradle/error-prone.gradle diff --git a/build.gradle b/build.gradle index a20f2b4c74..9a905550cf 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,7 @@ repositories { apply from: rootProject.file('gradle/java-publish.gradle') apply from: rootProject.file('gradle/changelog.gradle') allprojects { + apply from: rootProject.file('gradle/error-prone.gradle') apply from: rootProject.file('gradle/rewrite.gradle') apply from: rootProject.file('gradle/spotless.gradle') } diff --git a/gradle/error-prone.gradle b/gradle/error-prone.gradle new file mode 100644 index 0000000000..029ac4f324 --- /dev/null +++ b/gradle/error-prone.gradle @@ -0,0 +1,30 @@ +import static java.lang.System.getenv + +apply plugin: 'net.ltgt.errorprone' + +dependencies { + errorprone('com.google.errorprone:error_prone_core:2.42.0') + errorprone('tech.picnic.error-prone-support:error-prone-contrib:0.25.0') + constraints { + errorprone('com.google.guava:guava') { + version { + require('33.4.8-jre') + } + because('Older versions use deprecated methods in sun.misc.Unsafe') + // https://github.com/junit-team/junit-framework/pull/5039#discussion_r2414490581 + } + } +} + +tasks.withType(JavaCompile).configureEach { + options.errorprone { + disableAllChecks = true // consider removal to avoid error prone error´s, following convention over configuration. + error('RedundantStringConversion') + if (!getenv().containsKey('CI') && getenv('IN_PLACE')?.toBoolean()) { + errorproneArgs.addAll( + '-XepPatchLocation:IN_PLACE', + '-XepPatchChecks:RedundantStringConversion' + ) + } + } +} diff --git a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java index d205e14039..8697ca68c3 100644 --- a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java +++ b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java @@ -134,7 +134,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/biome/BiomeExecutableDownloader.java b/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java index 8a9c6923c0..ae090d3e4a 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java @@ -261,7 +261,7 @@ private Path getChecksumPath(Path file) { var parent = file.getParent(); var base = parent != null ? parent : file; var fileName = file.getFileName(); - var checksumName = fileName != null ? fileName.toString() + ".sha256" : "checksum.sha256"; + var checksumName = fileName != null ? fileName + ".sha256" : "checksum.sha256"; return base.resolve(checksumName); } 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 f80b084c91..de692a5e4e 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 @@ -186,7 +186,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/settings.gradle b/settings.gradle index 03e841f0ae..5b63b1a24d 100644 --- a/settings.gradle +++ b/settings.gradle @@ -23,6 +23,7 @@ plugins { id 'com.gradle.develocity' version '4.2.1' // https://github.com/equodev/equo-ide/blob/main/plugin-gradle/CHANGELOG.md id 'dev.equo.ide' version '1.7.8' apply false + id 'net.ltgt.errorprone' version '4.3.0' apply false id 'org.openrewrite.rewrite' version '7.17.0' apply false } diff --git a/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java b/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java index 4d0a340f42..5d393f6e28 100644 --- a/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java +++ b/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java @@ -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()) { From 74faf9602340e4f1f5bf0f767c1046deddc9859d Mon Sep 17 00:00:00 2001 From: Vincent Potucek Date: Mon, 13 Oct 2025 11:44:31 +0200 Subject: [PATCH 2/3] Add `ConstantNaming` --- gradle/error-prone.gradle | 4 ++-- lib/src/main/java/com/diffplug/spotless/ForeignExe.java | 2 +- .../diffplug/spotless/biome/BiomeExecutableDownloader.java | 2 +- .../com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java | 2 +- .../src/main/java/com/diffplug/spotless/ReflectionUtil.java | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/gradle/error-prone.gradle b/gradle/error-prone.gradle index 029ac4f324..9d19451f19 100644 --- a/gradle/error-prone.gradle +++ b/gradle/error-prone.gradle @@ -19,11 +19,11 @@ dependencies { tasks.withType(JavaCompile).configureEach { options.errorprone { disableAllChecks = true // consider removal to avoid error prone error´s, following convention over configuration. - error('RedundantStringConversion') + error('ConstantNaming') if (!getenv().containsKey('CI') && getenv('IN_PLACE')?.toBoolean()) { errorproneArgs.addAll( '-XepPatchLocation:IN_PLACE', - '-XepPatchChecks:RedundantStringConversion' + '-XepPatchChecks:ConstantNaming' ) } } diff --git a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java index 8697ca68c3..d205e14039 100644 --- a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java +++ b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java @@ -134,7 +134,7 @@ private RuntimeException exceptionFmt(String msgPrimary, ProcessRunner.Result cm errorMsg.append(msgFix); errorMsg.append('\n'); } - errorMsg.append(cmd); + errorMsg.append(cmd.toString()); return new RuntimeException(errorMsg.toString()); } } diff --git a/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java b/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java index ae090d3e4a..8a9c6923c0 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java @@ -261,7 +261,7 @@ private Path getChecksumPath(Path file) { var parent = file.getParent(); var base = parent != null ? parent : file; var fileName = file.getFileName(); - var checksumName = fileName != null ? fileName + ".sha256" : "checksum.sha256"; + var checksumName = fileName != null ? fileName.toString() + ".sha256" : "checksum.sha256"; return base.resolve(checksumName); } 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 de692a5e4e..f80b084c91 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 @@ -186,7 +186,7 @@ else if (contains(singleLineCommentStart, fChar)) { s.append(fChar); } } - return new FormatterToken(TokenType.COMMAND, word + s, start_pos); + return new FormatterToken(TokenType.COMMAND, word + s.toString(), start_pos); } if (sqlDialect.getKeywordType(word) != null) { return new FormatterToken(TokenType.KEYWORD, word, start_pos); diff --git a/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java b/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java index 5d393f6e28..4d0a340f42 100644 --- a/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java +++ b/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java @@ -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()); + System.out.print(" " + method.getReturnType().toString()); System.out.print(" " + method.getName() + "("); Iterator paramIter = Arrays.asList(method.getParameters()).iterator(); while (paramIter.hasNext()) { From 403659e72546d362d8e6315b459db30d5520c7c9 Mon Sep 17 00:00:00 2001 From: Vincent Potucek Date: Mon, 13 Oct 2025 11:46:54 +0200 Subject: [PATCH 3/3] Add `ConstantNaming` --- gradle/error-prone.gradle | 8 ++-- .../compat/KtLintCompat0Dot49Dot0Adapter.java | 2 +- .../compat/KtLintCompat0Dot50Dot0Adapter.java | 2 +- .../compat/KtLintCompat1Dot0Dot0Adapter.java | 2 +- .../com/diffplug/spotless/FileSignature.java | 4 +- .../java/com/diffplug/spotless/Formatter.java | 4 +- .../java/com/diffplug/spotless/JarState.java | 4 +- .../com/diffplug/spotless/LineEnding.java | 12 +++--- .../java/com/diffplug/spotless/LintState.java | 4 +- .../com/diffplug/spotless/SpotlessCache.java | 12 +++--- .../biome/BiomeExecutableDownloader.java | 24 ++++++------ .../spotless/biome/BiomeSettings.java | 4 +- .../diffplug/spotless/biome/BiomeStep.java | 12 +++--- .../spotless/java/FormatAnnotationsStep.java | 24 ++++++------ .../spotless/npm/EslintFormatterStep.java | 10 ++--- .../spotless/npm/ExclusiveFolderAccess.java | 4 +- .../com/diffplug/spotless/npm/NodeApp.java | 12 +++--- .../NodeModulesCachingNpmProcessFactory.java | 10 ++--- .../diffplug/spotless/npm/NodeServeApp.java | 6 +-- .../npm/NpmFormatterStepStateBase.java | 14 +++---- .../spotless/npm/PrettierFormatterStep.java | 8 ++-- .../com/diffplug/spotless/npm/ShadowCopy.java | 22 +++++------ .../spotless/npm/TsFmtFormatterStep.java | 4 +- .../spotless/rdf/ReflectionHelper.java | 6 +-- .../sql/dbeaver/SQLTokenizedFormatter.java | 10 ++--- .../spotless/sql/dbeaver/SQLTokensParser.java | 16 ++++---- .../glue/pom/SortPomFormatterFunc.java | 8 ++-- .../gradle/spotless/FormatExtension.java | 4 +- .../gradle/spotless/GradleProvisioner.java | 2 +- .../spotless/maven/kotlin/Ktlint.java | 6 +-- .../diffplug/spotless/TestProvisioner.java | 12 +++--- .../diffplug/spotless/FileSignatureTest.java | 16 ++++---- .../generic/LicenseHeaderStepTest.java | 38 +++++++++---------- .../spotless/markdown/FlexmarkStepTest.java | 4 +- 34 files changed, 165 insertions(+), 165 deletions(-) diff --git a/gradle/error-prone.gradle b/gradle/error-prone.gradle index 9d19451f19..b717762324 100644 --- a/gradle/error-prone.gradle +++ b/gradle/error-prone.gradle @@ -19,12 +19,12 @@ dependencies { tasks.withType(JavaCompile).configureEach { options.errorprone { disableAllChecks = true // consider removal to avoid error prone error´s, following convention over configuration. - error('ConstantNaming') + //error('ConstantNaming') if (!getenv().containsKey('CI') && getenv('IN_PLACE')?.toBoolean()) { errorproneArgs.addAll( - '-XepPatchLocation:IN_PLACE', - '-XepPatchChecks:ConstantNaming' - ) + '-XepPatchLocation:IN_PLACE', + '-XepPatchChecks:ConstantNaming' + ) } } } diff --git a/lib/src/compatKtLint0Dot49Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot49Dot0Adapter.java b/lib/src/compatKtLint0Dot49Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot49Dot0Adapter.java index f4c1e04af7..e97a0c78b2 100644 --- a/lib/src/compatKtLint0Dot49Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot49Dot0Adapter.java +++ b/lib/src/compatKtLint0Dot49Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot49Dot0Adapter.java @@ -55,7 +55,7 @@ public class KtLintCompat0Dot49Dot0Adapter implements KtLintCompatAdapter { - private static final Logger logger = LoggerFactory.getLogger(KtLintCompat0Dot49Dot0Adapter.class); + private static final Logger LOGGER = LoggerFactory.getLogger(KtLintCompat0Dot49Dot0Adapter.class); private static final List> DEFAULT_EDITOR_CONFIG_PROPERTIES; diff --git a/lib/src/compatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0Adapter.java b/lib/src/compatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0Adapter.java index 951b82704a..767408bf83 100644 --- a/lib/src/compatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0Adapter.java +++ b/lib/src/compatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0Adapter.java @@ -55,7 +55,7 @@ public class KtLintCompat0Dot50Dot0Adapter implements KtLintCompatAdapter { - private static final Logger logger = LoggerFactory.getLogger(KtLintCompat0Dot50Dot0Adapter.class); + private static final Logger LOGGER = LoggerFactory.getLogger(KtLintCompat0Dot50Dot0Adapter.class); private static final List> DEFAULT_EDITOR_CONFIG_PROPERTIES; diff --git a/lib/src/compatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0Adapter.java b/lib/src/compatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0Adapter.java index 86387d0d6b..56e8022ad5 100644 --- a/lib/src/compatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0Adapter.java +++ b/lib/src/compatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0Adapter.java @@ -54,7 +54,7 @@ public class KtLintCompat1Dot0Dot0Adapter implements KtLintCompatAdapter { - private static final Logger logger = LoggerFactory.getLogger(KtLintCompat1Dot0Dot0Adapter.class); + private static final Logger LOGGER = LoggerFactory.getLogger(KtLintCompat1Dot0Dot0Adapter.class); private static final List> DEFAULT_EDITOR_CONFIG_PROPERTIES; diff --git a/lib/src/main/java/com/diffplug/spotless/FileSignature.java b/lib/src/main/java/com/diffplug/spotless/FileSignature.java index f0332aef1f..d90fc145c3 100644 --- a/lib/src/main/java/com/diffplug/spotless/FileSignature.java +++ b/lib/src/main/java/com/diffplug/spotless/FileSignature.java @@ -146,11 +146,11 @@ public File getOnlyFile() { } } - private static final boolean machineIsWin = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win"); + private static final boolean MACHINE_IS_WIN = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win"); /** Returns true if this JVM is running on a windows machine. */ public static boolean machineIsWin() { - return machineIsWin; + return MACHINE_IS_WIN; } /** Transforms a native path to a unix one. */ diff --git a/lib/src/main/java/com/diffplug/spotless/Formatter.java b/lib/src/main/java/com/diffplug/spotless/Formatter.java index 941667adb4..26f4f61238 100644 --- a/lib/src/main/java/com/diffplug/spotless/Formatter.java +++ b/lib/src/main/java/com/diffplug/spotless/Formatter.java @@ -143,13 +143,13 @@ static void legacyErrorBehavior(Formatter formatter, File file, ValuePerStep> toFormat) { /** Should use {@link #createPolicy(File, Supplier)} instead, but this will work iff its a path-independent LineEnding policy. */ public Policy createPolicy() { switch (this) { - case PLATFORM_NATIVE: return _platformNativePolicy; + case PLATFORM_NATIVE: return _PLATFORM_NATIVE_POLICY; case WINDOWS: return WINDOWS_POLICY; case UNIX: return UNIX_POLICY; case MAC_CLASSIC: return MAC_CLASSIC_POLICY; @@ -152,9 +152,9 @@ static String getEndingFor(Reader reader) throws IOException { private static final Policy UNIX_POLICY = new ConstantLineEndingPolicy(UNIX.str()); private static final Policy MAC_CLASSIC_POLICY = new ConstantLineEndingPolicy(MAC_CLASSIC.str()); private static final Policy PRESERVE_POLICY = new PreserveLineEndingPolicy(); - private static final String _platformNative = System.getProperty("line.separator"); - private static final Policy _platformNativePolicy = new ConstantLineEndingPolicy(_platformNative); - private static final boolean nativeIsWin = _platformNative.equals(WINDOWS.str()); + private static final String _PLATFORM_NATIVE = System.getProperty("line.separator"); + private static final Policy _PLATFORM_NATIVE_POLICY = new ConstantLineEndingPolicy(_PLATFORM_NATIVE); + private static final boolean NATIVE_IS_WIN = _PLATFORM_NATIVE.equals(WINDOWS.str()); /** * @deprecated Using the system-native line endings to detect the windows operating system has turned out @@ -164,13 +164,13 @@ static String getEndingFor(Reader reader) throws IOException { */ @Deprecated public static boolean nativeIsWin() { - return nativeIsWin; + return NATIVE_IS_WIN; } /** Returns the standard line ending for this policy. */ public String str() { switch (this) { - case PLATFORM_NATIVE: return _platformNative; + case PLATFORM_NATIVE: return _PLATFORM_NATIVE; case WINDOWS: return "\r\n"; case UNIX: return "\n"; case MAC_CLASSIC: return "\r"; diff --git a/lib/src/main/java/com/diffplug/spotless/LintState.java b/lib/src/main/java/com/diffplug/spotless/LintState.java index bc4cf9e64b..b025ea3caa 100644 --- a/lib/src/main/java/com/diffplug/spotless/LintState.java +++ b/lib/src/main/java/com/diffplug/spotless/LintState.java @@ -197,10 +197,10 @@ public static LintState of(Formatter formatter, File file, byte[] rawBytes) { /** Returns the DirtyState which corresponds to {@code isClean()}. */ public static LintState clean() { - return isClean; + return IS_CLEAN; } - private static final LintState isClean = new LintState(DirtyState.clean(), null); + private static final LintState IS_CLEAN = new LintState(DirtyState.clean(), null); static Throwable formatStepCausedNoChange() { return FormatterCausedNoChange.INSTANCE; diff --git a/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java b/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java index 82cdd5d3c2..795f33f6e4 100644 --- a/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java +++ b/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java @@ -76,7 +76,7 @@ synchronized ClassLoader classloader(Serializable key, JarState state) { } static SpotlessCache instance() { - return instance; + return INSTANCE; } /** @@ -84,9 +84,9 @@ static SpotlessCache instance() { */ private static void clear() { List toDelete; - synchronized (instance) { - toDelete = new ArrayList<>(instance.cache.values()); - instance.cache.clear(); + synchronized (INSTANCE) { + toDelete = new ArrayList<>(INSTANCE.cache.values()); + INSTANCE.cache.clear(); } for (URLClassLoader classLoader : toDelete) { try { @@ -104,7 +104,7 @@ private static void clear() { * If {@code key} is null, the clear will always happen (as though null != null). */ public static boolean clearOnce(@Nullable Object key) { - synchronized (instance) { + synchronized (INSTANCE) { if (key == null) { lastClear = null; } else if (key.equals(lastClear)) { @@ -117,5 +117,5 @@ public static boolean clearOnce(@Nullable Object key) { return true; } - private static final SpotlessCache instance = new SpotlessCache(); + private static final SpotlessCache INSTANCE = new SpotlessCache(); } diff --git a/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java b/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java index 8a9c6923c0..5385f41d3b 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java @@ -42,7 +42,7 @@ * https://github.com/biomejs/biome. */ final class BiomeExecutableDownloader { - private static final Logger logger = LoggerFactory.getLogger(BiomeExecutableDownloader.class); + private static final Logger LOGGER = LoggerFactory.getLogger(BiomeExecutableDownloader.class); /** * The checksum algorithm to use for checking the integrity of downloaded files. @@ -106,7 +106,7 @@ public Path download(String version) throws IOException, InterruptedException { if (executableDir != null) { Files.createDirectories(executableDir); } - logger.info("Attempting to download Biome from '{}' to '{}'", url, executablePath); + LOGGER.info("Attempting to download Biome from '{}' to '{}'", url, executablePath); var request = HttpRequest.newBuilder(URI.create(url)).GET().build(); var handler = BodyHandlers.ofFile(executablePath, WRITE_OPTIONS); var response = HttpClient.newBuilder().followRedirects(Redirect.NORMAL).build().send(request, handler); @@ -118,7 +118,7 @@ public Path download(String version) throws IOException, InterruptedException { throw new IOException("Failed to download file from " + url + ", file is empty or does not exist"); } writeChecksumFile(downloadedFile, checksumPath); - logger.debug("Biome was downloaded successfully to '{}'", downloadedFile); + LOGGER.debug("Biome was downloaded successfully to '{}'", downloadedFile); return downloadedFile; } @@ -142,13 +142,13 @@ public Path download(String version) throws IOException, InterruptedException { */ public Path ensureDownloaded(String version) throws IOException, InterruptedException { var platform = Platform.guess(); - logger.debug("Ensuring that Biome for platform '{}' is downloaded", platform); + LOGGER.debug("Ensuring that Biome for platform '{}' is downloaded", platform); var existing = findDownloaded(version); if (existing.isPresent()) { - logger.debug("Biome was already downloaded, using executable at '{}'", existing.orElseThrow()); + LOGGER.debug("Biome was already downloaded, using executable at '{}'", existing.orElseThrow()); return existing.orElseThrow(); } else { - logger.debug("Biome was not yet downloaded, attempting to download executable"); + LOGGER.debug("Biome was not yet downloaded, attempting to download executable"); return download(version); } } @@ -169,7 +169,7 @@ public Path ensureDownloaded(String version) throws IOException, InterruptedExce public Optional findDownloaded(String version) throws IOException { var platform = Platform.guess(); var executablePath = getExecutablePath(version, platform); - logger.debug("Checking Biome executable at {}", executablePath); + LOGGER.debug("Checking Biome executable at {}", executablePath); return checkFileWithChecksum(executablePath) ? Optional.ofNullable(executablePath) : Optional.empty(); } @@ -183,26 +183,26 @@ public Optional findDownloaded(String version) throws IOException { */ private boolean checkFileWithChecksum(Path filePath) { if (!Files.exists(filePath)) { - logger.debug("File '{}' does not exist yet", filePath); + LOGGER.debug("File '{}' does not exist yet", filePath); return false; } if (Files.isDirectory(filePath)) { - logger.debug("File '{}' exists, but is a directory", filePath); + LOGGER.debug("File '{}' exists, but is a directory", filePath); return false; } var checksumPath = getChecksumPath(filePath); if (!Files.exists(checksumPath)) { - logger.debug("File '{}' exists, but checksum file '{}' does not", filePath, checksumPath); + LOGGER.debug("File '{}' exists, but checksum file '{}' does not", filePath, checksumPath); return false; } if (Files.isDirectory(checksumPath)) { - logger.debug("Checksum file '{}' exists, but is a directory", checksumPath); + LOGGER.debug("Checksum file '{}' exists, but is a directory", checksumPath); return false; } try { var actualChecksum = computeChecksum(filePath, CHECKSUM_ALGORITHM); var expectedChecksum = readTextFile(checksumPath, StandardCharsets.ISO_8859_1); - logger.debug("Expected checksum: {}, actual checksum: {}", expectedChecksum, actualChecksum); + LOGGER.debug("Expected checksum: {}, actual checksum: {}", expectedChecksum, actualChecksum); return Objects.equals(expectedChecksum, actualChecksum); } catch (final IOException ignored) { return false; diff --git a/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java b/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java index 6d1db090b3..44948a1294 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java @@ -22,7 +22,7 @@ * Settings and constants for Biome to use. */ public final class BiomeSettings { - private static final Logger logger = LoggerFactory.getLogger(BiomeSettings.class); + private static final Logger LOGGER = LoggerFactory.getLogger(BiomeSettings.class); private static final String CONFIG_NAME = "biome.json"; private static final String DEFAULT_VERSION = "1.2.0"; @@ -106,7 +106,7 @@ public static boolean versionHigherThanOrEqualTo(String version, int major, int } return actualMajor == major && actualMinor == minor && actualPatch == patch; } catch (final Exception e) { - logger.warn("Failed to parse biome version string '{}'. Expected format is 'major.minor.patch'.", version, e); + LOGGER.warn("Failed to parse biome version string '{}'. Expected format is 'major.minor.patch'.", version, e); return false; } } diff --git a/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java b/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java index 66b69112d5..2f80fba8f4 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java @@ -43,7 +43,7 @@ * the network when no executable path is provided explicitly. */ public final class BiomeStep { - private static final Logger logger = LoggerFactory.getLogger(BiomeStep.class); + private static final Logger LOGGER = LoggerFactory.getLogger(BiomeStep.class); /** * Path to the directory with the {@code biome.json} config file, can be @@ -136,7 +136,7 @@ private static void attemptToAddPosixPermission(Path file, PosixFilePermission p newPermissions.add(permission); Files.setPosixFilePermissions(file, newPermissions); } catch (final Exception ignore) { - logger.debug("Unable to add POSIX permission '{}' to file '{}'", permission, file); + LOGGER.debug("Unable to add POSIX permission '{}' to file '{}'", permission, file); } } @@ -298,7 +298,7 @@ private State createState() throws IOException, InterruptedException { var resolvedPathToExe = resolveExe(); validateBiomeExecutable(resolvedPathToExe); validateBiomeConfigPath(configPath, version); - logger.debug("Using Biome executable located at '{}'", resolvedPathToExe); + LOGGER.debug("Using Biome executable located at '{}'", resolvedPathToExe); var exeSignature = FileSignature.signAsList(Set.of(new File(resolvedPathToExe))); makeExecutable(resolvedPathToExe); return new State(resolvedPathToExe, exeSignature, configPath, language); @@ -421,13 +421,13 @@ private String[] buildBiomeCommand(File file) { private String format(ProcessRunner runner, String input, File file) throws IOException, InterruptedException { var stdin = input.getBytes(StandardCharsets.UTF_8); var args = buildBiomeCommand(file); - if (logger.isDebugEnabled()) { - logger.debug("Running Biome command to format code: '{}'", String.join(", ", args)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Running Biome command to format code: '{}'", String.join(", ", args)); } var runnerResult = runner.exec(stdin, args); var stdErr = runnerResult.stdErrUtf8(); if (!stdErr.isEmpty()) { - logger.warn("Biome stderr ouptut for file '{}'\n{}", file, stdErr.trim()); + LOGGER.warn("Biome stderr ouptut for file '{}'\n{}", file, stdErr.trim()); } var formatted = runnerResult.assertExitZero(StandardCharsets.UTF_8); // When biome encounters an ignored file, it does not output any formatted code 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 bfdfc0ba09..587f3827ba 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java @@ -47,7 +47,7 @@ public final class FormatAnnotationsStep implements Serializable { * A type annotation is an annotation that is meta-annotated with @Target({ElementType.TYPE_USE}). * A type annotation should be formatted on the same line as the type it qualifies. */ - private static final List defaultTypeAnnotations = + private static final List DEFAULT_TYPE_ANNOTATIONS = // Use simple names because Spotless has no access to the // fully-qualified names or the definitions of the type qualifiers. Arrays.asList( @@ -431,21 +431,21 @@ private static final class State implements Serializable { @Serial private static final long serialVersionUID = 1L; - private final Set typeAnnotations = new HashSet<>(defaultTypeAnnotations); + private final Set typeAnnotations = new HashSet<>(DEFAULT_TYPE_ANNOTATIONS); // group 1 is the basename of the annotation. - private static final String annoNoArgRegex = "@(?:[A-Za-z_][A-Za-z0-9_.]*\\.)?([A-Za-z_][A-Za-z0-9_]*)"; + private static final String ANNO_NO_ARG_REGEX = "@(?:[A-Za-z_][A-Za-z0-9_.]*\\.)?([A-Za-z_][A-Za-z0-9_]*)"; // 3 non-empty cases: () (".*") (.*) - private static final String annoArgRegex = "(?:\\(\\)|\\(\"[^\"]*\"\\)|\\([^\")][^)]*\\))?"; + private static final String ANNO_ARG_REGEX = "(?:\\(\\)|\\(\"[^\"]*\"\\)|\\([^\")][^)]*\\))?"; // group 1 is the basename of the annotation. - private static final String annoRegex = annoNoArgRegex + annoArgRegex; - private static final String trailingAnnoRegex = annoRegex + "$"; - private static final Pattern trailingAnnoPattern = Pattern.compile(trailingAnnoRegex); + private static final String ANNO_REGEX = ANNO_NO_ARG_REGEX + ANNO_ARG_REGEX; + private static final String TRAILING_ANNO_REGEX = ANNO_REGEX + "$"; + private static final Pattern TRAILING_ANNO_PATTERN = Pattern.compile(TRAILING_ANNO_REGEX); // Heuristic: matches if the line might be within a //, /*, or Javadoc comment. - private static final Pattern withinCommentPattern = Pattern.compile("//|/\\*(?!.*/*/)|^[ \t]*\\*[ \t]"); + private static final Pattern WITHIN_COMMENT_PATTERN = Pattern.compile("//|/\\*(?!.*/*/)|^[ \t]*\\*[ \t]"); // Don't move an annotation to the start of a comment line. - private static final Pattern startsWithCommentPattern = Pattern.compile("^[ \t]*(//|/\\*$|/\\*|void\\b)"); + private static final Pattern STARTS_WITH_COMMENT_PATTERN = Pattern.compile("^[ \t]*(//|/\\*$|/\\*|void\\b)"); /** * @param addedTypeAnnotations simple names to add to Spotless's default list @@ -473,7 +473,7 @@ String fixupTypeAnnotations(String unixStr) { String line = lines[i]; if (endsWithTypeAnnotation(line)) { String nextLine = lines[i + 1]; - if (startsWithCommentPattern.matcher(nextLine).find()) { + if (STARTS_WITH_COMMENT_PATTERN.matcher(nextLine).find()) { continue; } lines[i] = ""; @@ -490,14 +490,14 @@ String fixupTypeAnnotations(String unixStr) { boolean endsWithTypeAnnotation(String unixLine) { // Remove trailing newline. String line = unixLine.replaceAll("\\s+$", ""); - Matcher m = trailingAnnoPattern.matcher(line); + Matcher m = TRAILING_ANNO_PATTERN.matcher(line); if (!m.find()) { return false; } String preceding = line.substring(0, m.start()); String basename = m.group(1); - if (withinCommentPattern.matcher(preceding).find()) { + if (WITHIN_COMMENT_PATTERN.matcher(preceding).find()) { return false; } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java index 04c07e793f..8244a36bfb 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java @@ -40,7 +40,7 @@ public final class EslintFormatterStep { - private static final Logger logger = LoggerFactory.getLogger(EslintFormatterStep.class); + private static final Logger LOGGER = LoggerFactory.getLogger(EslintFormatterStep.class); public static final String NAME = "eslint-format"; @@ -109,7 +109,7 @@ protected void prepareNodeServerLayout(NodeServerLayout nodeServerLayout) throws // If any config files are provided, we need to make sure they are at the same location as the node modules // as eslint will try to resolve plugin/config names relatively to the config file location and some // eslint configs contain relative paths to additional config files (such as tsconfig.json e.g.) - logger.debug("Copying config file <{}> to <{}> and using the copy", origEslintConfig.getEslintConfigPath(), nodeServerLayout.nodeModulesDir()); + LOGGER.debug("Copying config file <{}> to <{}> and using the copy", origEslintConfig.getEslintConfigPath(), nodeServerLayout.nodeModulesDir()); File configFileCopy = NpmResourceHelper.copyFileToDir(origEslintConfig.getEslintConfigPath(), nodeServerLayout.nodeModulesDir()); this.eslintConfigInUse = this.origEslintConfig.withEslintConfigPath(configFileCopy).verify(); } @@ -119,7 +119,7 @@ protected void prepareNodeServerLayout(NodeServerLayout nodeServerLayout) throws @Nonnull public FormatterFunc createFormatterFunc() { try { - logger.info("Creating formatter function (starting server)"); + LOGGER.info("Creating formatter function (starting server)"); Runtime runtime = toRuntime(); ServerProcessInfo eslintRestServer = runtime.npmRunServer(); EslintRestService restService = new EslintRestService(eslintRestServer.getBaseUrl()); @@ -130,11 +130,11 @@ public FormatterFunc createFormatterFunc() { } private void endServer(BaseNpmRestService restService, ServerProcessInfo restServer) throws Exception { - logger.info("Closing formatting function (ending server)."); + LOGGER.info("Closing formatting function (ending server)."); try { restService.shutdown(); } catch (Throwable t) { - logger.info("Failed to request shutdown of rest service via api. Trying via process.", t); + LOGGER.info("Failed to request shutdown of rest service via api. Trying via process.", t); } restServer.close(); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java b/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java index 2b8c542ba8..8965e700b2 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java @@ -39,7 +39,7 @@ static ExclusiveFolderAccess forFolder(@Nonnull String path) { final class ExclusiveFolderAccessSharedMutex implements ExclusiveFolderAccess { - private static final ConcurrentHashMap mutexes = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap MUTEXES = new ConcurrentHashMap<>(); private final String path; @@ -48,7 +48,7 @@ private ExclusiveFolderAccessSharedMutex(@Nonnull String path) { } private Lock getMutex() { - return mutexes.computeIfAbsent(path, k -> new ReentrantLock()); + return MUTEXES.computeIfAbsent(path, k -> new ReentrantLock()); } @Override diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeApp.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeApp.java index 19eb584c57..ffe8e2bf13 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeApp.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeApp.java @@ -29,9 +29,9 @@ public class NodeApp { - private static final Logger logger = LoggerFactory.getLogger(NodeApp.class); + private static final Logger LOGGER = LoggerFactory.getLogger(NodeApp.class); - private static final TimedLogger timedLogger = TimedLogger.forLogger(logger); + private static final TimedLogger TIMED_LOGGER = TimedLogger.forLogger(LOGGER); @Nonnull protected final NodeServerLayout nodeServerLayout; @@ -54,10 +54,10 @@ public NodeApp(@Nonnull NodeServerLayout nodeServerLayout, @Nonnull NpmConfig np private static NpmProcessFactory processFactory(NpmFormatterStepLocations formatterStepLocations) { if (formatterStepLocations.cacheDir() != null) { - logger.info("Caching npm install results in {}.", formatterStepLocations.cacheDir()); + LOGGER.info("Caching npm install results in {}.", formatterStepLocations.cacheDir()); return NodeModulesCachingNpmProcessFactory.create(formatterStepLocations.cacheDir()); } - logger.debug("Not caching npm install results."); + LOGGER.debug("Not caching npm install results."); return StandardNpmProcessFactory.INSTANCE; } @@ -70,7 +70,7 @@ boolean needsPrepareNodeAppLayout() { } void prepareNodeAppLayout() { - timedLogger.withInfo("Preparing {} for npm step {}.", this.nodeServerLayout, getClass().getName()).run(() -> { + TIMED_LOGGER.withInfo("Preparing {} for npm step {}.", this.nodeServerLayout, getClass().getName()).run(() -> { NpmResourceHelper.assertDirectoryExists(nodeServerLayout.nodeModulesDir()); NpmResourceHelper.writeUtf8StringToFile(nodeServerLayout.packageJsonFile(), this.npmConfig.getPackageJsonContent()); if (this.npmConfig.getServeScriptContent() != null) { @@ -87,7 +87,7 @@ void prepareNodeAppLayout() { } void npmInstall() { - timedLogger.withInfo("Installing npm dependencies for {} with {}.", this.nodeServerLayout, this.npmProcessFactory.describe()) + TIMED_LOGGER.withInfo("Installing npm dependencies for {} with {}.", this.nodeServerLayout, this.npmProcessFactory.describe()) .run(this::optimizedNpmInstall); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java index ae8ff3afa8..c483e0c1e2 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java @@ -29,9 +29,9 @@ public final class NodeModulesCachingNpmProcessFactory implements NpmProcessFactory { - private static final Logger logger = LoggerFactory.getLogger(NodeModulesCachingNpmProcessFactory.class); + private static final Logger LOGGER = LoggerFactory.getLogger(NodeModulesCachingNpmProcessFactory.class); - private static final TimedLogger timedLogger = TimedLogger.forLogger(logger); + private static final TimedLogger TIMED_LOGGER = TimedLogger.forLogger(LOGGER); private final File cacheDir; @@ -84,11 +84,11 @@ public CachingNmpInstall(NpmProcess actualNpmInstallProcess, NodeServerLayout no public Result waitFor() { String entryName = entryName(); if (shadowCopy.entryExists(entryName, NodeServerLayout.NODE_MODULES)) { - timedLogger.withInfo("Using cached node_modules for {} from {}", entryName, cacheDir) + TIMED_LOGGER.withInfo("Using cached node_modules for {} from {}", entryName, cacheDir) .run(() -> shadowCopy.copyEntryInto(entryName(), NodeServerLayout.NODE_MODULES, nodeServerLayout.nodeModulesDir())); return new CachedResult(); } else { - Result result = timedLogger.withInfo("calling actual npm install {}", actualNpmInstallProcess.describe()) + Result result = TIMED_LOGGER.withInfo("calling actual npm install {}", actualNpmInstallProcess.describe()) .call(actualNpmInstallProcess::waitFor); assert result.exitCode() == 0; storeShadowCopy(entryName); @@ -97,7 +97,7 @@ public Result waitFor() { } private void storeShadowCopy(String entryName) { - timedLogger.withInfo("Caching node_modules for {} in {}", entryName, cacheDir) + TIMED_LOGGER.withInfo("Caching node_modules for {} in {}", entryName, cacheDir) .run(() -> shadowCopy.addEntry(entryName(), new File(nodeServerLayout.nodeModulesDir(), NodeServerLayout.NODE_MODULES))); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeServeApp.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeServeApp.java index 3e2efd43e8..c457807560 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeServeApp.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeServeApp.java @@ -26,16 +26,16 @@ public class NodeServeApp extends NodeApp { - private static final Logger logger = LoggerFactory.getLogger(NodeApp.class); + private static final Logger LOGGER = LoggerFactory.getLogger(NodeApp.class); - private static final TimedLogger timedLogger = TimedLogger.forLogger(logger); + private static final TimedLogger TIMED_LOGGER = TimedLogger.forLogger(LOGGER); public NodeServeApp(@Nonnull NodeServerLayout nodeServerLayout, @Nonnull NpmConfig npmConfig, @Nonnull NpmFormatterStepLocations formatterStepLocations) { super(nodeServerLayout, npmConfig, formatterStepLocations); } ProcessRunner.LongRunningProcess startNpmServeProcess(UUID nodeServerInstanceId) { - return timedLogger.withInfo("Starting npm based server in {} with {}.", this.nodeServerLayout.nodeModulesDir(), this.npmProcessFactory.describe()) + return TIMED_LOGGER.withInfo("Starting npm based server in {} with {}.", this.nodeServerLayout.nodeModulesDir(), this.npmProcessFactory.describe()) .call(() -> npmProcessFactory.createNpmServeProcess(nodeServerLayout, formatterStepLocations, nodeServerInstanceId).start()); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java index dcd79d1ee0..7fc8f2033b 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java @@ -39,9 +39,9 @@ abstract class NpmFormatterStepStateBase implements Serializable { - private static final Logger logger = LoggerFactory.getLogger(NpmFormatterStepStateBase.class); + private static final Logger LOGGER = LoggerFactory.getLogger(NpmFormatterStepStateBase.class); - private static final TimedLogger timedLogger = TimedLogger.forLogger(logger); + private static final TimedLogger TIMED_LOGGER = TimedLogger.forLogger(LOGGER); @Serial private static final long serialVersionUID = 1460749955865959948L; @@ -132,11 +132,11 @@ protected ServerProcessInfo npmRunServer() throws ServerStartException, IOExcept if (server.isAlive()) { server.destroyForcibly(); ProcessRunner.Result result = server.result(); - logger.info("Launching npm server process failed. Process result:\n{}", result); + LOGGER.info("Launching npm server process failed. Process result:\n{}", result); } } catch (Throwable t) { ProcessRunner.Result result = ThrowingEx.get(server::result); - logger.debug("Unable to forcibly end the server process. Process result:\n{}", result, t); + LOGGER.debug("Unable to forcibly end the server process. Process result:\n{}", result, t); } throw timeoutException; } @@ -194,15 +194,15 @@ public String getBaseUrl() { @Override public void close() throws Exception { try { - logger.trace("Closing npm server in directory <{}> and port <{}>", + LOGGER.trace("Closing npm server in directory <{}> and port <{}>", serverPortFile.getParent(), serverPort); if (server.isAlive()) { boolean ended = server.waitFor(5, TimeUnit.SECONDS); if (!ended) { - logger.info("Force-Closing npm server in directory <{}> and port <{}>", serverPortFile.getParent(), serverPort); + LOGGER.info("Force-Closing npm server in directory <{}> and port <{}>", serverPortFile.getParent(), serverPort); server.destroyForcibly().waitFor(); - logger.trace("Force-Closing npm server in directory <{}> and port <{}> -- Finished", serverPortFile.getParent(), serverPort); + LOGGER.trace("Force-Closing npm server in directory <{}> and port <{}> -- Finished", serverPortFile.getParent(), serverPort); } } } finally { 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 34f8b92857..e272b2ebdf 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java @@ -36,7 +36,7 @@ public final class PrettierFormatterStep { - private static final Logger logger = LoggerFactory.getLogger(PrettierFormatterStep.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PrettierFormatterStep.class); public static final String NAME = "prettier-format"; @@ -86,7 +86,7 @@ private static class State extends NpmFormatterStepStateBase implements Serializ @Nonnull public FormatterFunc createFormatterFunc() { try { - logger.info("creating formatter function (starting server)"); + LOGGER.info("creating formatter function (starting server)"); ServerProcessInfo prettierRestServer = toRuntime().npmRunServer(); PrettierRestService restService = new PrettierRestService(prettierRestServer.getBaseUrl()); String prettierConfigOptions = restService.resolveConfig(this.prettierConfig.getPrettierConfigPath(), this.prettierConfig.getOptions()); @@ -97,11 +97,11 @@ public FormatterFunc createFormatterFunc() { } private void endServer(PrettierRestService restService, ServerProcessInfo restServer) throws Exception { - logger.info("Closing formatting function (ending server)."); + LOGGER.info("Closing formatting function (ending server)."); try { restService.shutdown(); } catch (Throwable t) { - logger.info("Failed to request shutdown of rest service via api. Trying via process.", t); + LOGGER.info("Failed to request shutdown of rest service via api. Trying via process.", t); } restServer.close(); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java b/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java index 6adf3a28dd..af7d956c16 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java @@ -40,7 +40,7 @@ class ShadowCopy { - private static final Logger logger = LoggerFactory.getLogger(ShadowCopy.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ShadowCopy.class); private final Supplier shadowCopyRootSupplier; @@ -59,13 +59,13 @@ private File shadowCopyRoot() { public void addEntry(String key, File orig) { File target = entry(key, orig.getName()); if (target.exists()) { - logger.debug("Shadow copy entry already exists, not overwriting: {}", key); + LOGGER.debug("Shadow copy entry already exists, not overwriting: {}", key); } else { try { storeEntry(key, orig, target); } catch (Throwable ex) { // Log but don't fail - logger.warn("Unable to store cache entry for {}", key, ex); + LOGGER.warn("Unable to store cache entry for {}", key, ex); } } } @@ -75,20 +75,20 @@ private void storeEntry(String key, File orig, File target) throws IOException { // Create a temp directory in the same directory as target Files.createDirectories(target.toPath().getParent()); Path tempDirectory = Files.createTempDirectory(target.toPath().getParent(), key); - logger.debug("Will store entry {} to temporary directory {}, which is a sibling of the ultimate target {}", orig, tempDirectory, target); + LOGGER.debug("Will store entry {} to temporary directory {}, which is a sibling of the ultimate target {}", orig, tempDirectory, target); try { // Copy orig to temp dir Files.walkFileTree(orig.toPath(), new CopyDirectoryRecursively(tempDirectory, orig.toPath())); try { - logger.debug("Finished storing entry {}. Atomically moving temporary directory {} into final place {}", key, tempDirectory, target); + LOGGER.debug("Finished storing entry {}. Atomically moving temporary directory {} into final place {}", key, tempDirectory, target); // Atomically rename the completed cache entry into place Files.move(tempDirectory, target.toPath(), StandardCopyOption.ATOMIC_MOVE); } catch (FileAlreadyExistsException | DirectoryNotEmptyException e) { // Someone already beat us to it - logger.debug("Shadow copy entry now exists, not overwriting: {}", key); + LOGGER.debug("Shadow copy entry now exists, not overwriting: {}", key); } catch (AtomicMoveNotSupportedException e) { - logger.warn("The filesystem at {} does not support atomic moves. Spotless cannot safely cache on such a system due to race conditions. Caching has been skipped.", target.toPath().getParent(), e); + LOGGER.warn("The filesystem at {} does not support atomic moves. Spotless cannot safely cache on such a system due to race conditions. Caching has been skipped.", target.toPath().getParent(), e); } } finally { // Best effort to clean up @@ -96,7 +96,7 @@ private void storeEntry(String key, File orig, File target) throws IOException { try { Files.walkFileTree(tempDirectory, new DeleteDirectoryRecursively()); } catch (Throwable ex) { - logger.warn("Ignoring error while cleaning up temporary copy", ex); + LOGGER.warn("Ignoring error while cleaning up temporary copy", ex); } } } @@ -113,7 +113,7 @@ private File entry(String key, String origName) { public File copyEntryInto(String key, String origName, File targetParentFolder) { File target = Path.of(targetParentFolder.getAbsolutePath(), origName).toFile(); if (target.exists()) { - logger.warn("Shadow copy destination already exists, deleting! {}: {}", key, target); + LOGGER.warn("Shadow copy destination already exists, deleting! {}: {}", key, target); ThrowingEx.run(() -> Files.walkFileTree(target.toPath(), new DeleteDirectoryRecursively())); } // copy directory "orig" to "target" using hard links if possible or a plain copy otherwise @@ -151,10 +151,10 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO Files.createLink(target.resolve(orig.relativize(file)), file); return super.visitFile(file, attrs); } catch (UnsupportedOperationException | SecurityException | FileSystemException e) { - logger.debug("Shadow copy entry does not support hard links: {}. Switching to 'copy'.", file, e); + LOGGER.debug("Shadow copy entry does not support hard links: {}. Switching to 'copy'.", file, e); tryHardLink = false; // remember that hard links are not supported } catch (IOException e) { - logger.debug("Shadow copy entry failed to create hard link: {}. Switching to 'copy'.", file, e); + LOGGER.debug("Shadow copy entry failed to create hard link: {}. Switching to 'copy'.", file, e); tryHardLink = false; // remember that hard links are not supported } } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java index 787b14c9c9..2e9fc13b58 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java @@ -38,7 +38,7 @@ public final class TsFmtFormatterStep { - private static final Logger logger = LoggerFactory.getLogger(TsFmtFormatterStep.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TsFmtFormatterStep.class); public static final String NAME = "tsfmt-format"; @@ -121,7 +121,7 @@ private void endServer(TsFmtRestService restService, ServerProcessInfo restServe try { restService.shutdown(); } catch (Throwable t) { - logger.info("Failed to request shutdown of rest service via api. Trying via process.", t); + LOGGER.info("Failed to request shutdown of rest service via api. Trying via process.", t); } restServer.close(); } diff --git a/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java b/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java index 51f2aff90d..061062434f 100644 --- a/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java @@ -43,7 +43,7 @@ import org.slf4j.LoggerFactory; class ReflectionHelper { - private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private final RdfFormatterStep.State state; private final ClassLoader classLoader; private final Class JenaRdfDataMgrClass; @@ -202,10 +202,10 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl long col = (long) args[2]; String severity = method.getName(); if ("warning".equals(severity) && !state.getConfig().isFailOnWarning()) { - logger.warn("{}({},{}): {}", this.filePath, line, col, message); + LOGGER.warn("{}({},{}): {}", this.filePath, line, col, message); } else { if ("warning".equals(severity)) { - logger.error("Formatter fails because of a parser warning. To make the formatter succeed in" + LOGGER.error("Formatter fails because of a parser warning. To make the formatter succeed in" + "the presence of warnings, set the configuration parameter 'failOnWarning' to 'false' (default: 'true')"); } throw new RuntimeException( 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 53d1cae485..52665bf716 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 @@ -37,7 +37,7 @@ public class SQLTokenizedFormatter { private static final String[] JOIN_BEGIN = {"LEFT", "RIGHT", "INNER", "OUTER", "JOIN"}; - private static final SQLDialect sqlDialect = SQLDialect.INSTANCE; + private static final SQLDialect SQL_DIALECT = SQLDialect.INSTANCE; private DBeaverSQLFormatterConfiguration formatterCfg; private List functionBracket = new ArrayList<>(); private List statementDelimiters = new ArrayList<>(2); @@ -251,7 +251,7 @@ private List format(final List argList) { } } else if (token.getType() == TokenType.COMMENT) { boolean isComment = false; - String[] slComments = sqlDialect.getSingleLineComments(); + String[] slComments = SQL_DIALECT.getSingleLineComments(); for (String slc : slComments) { if (token.getString().startsWith(slc)) { isComment = true; @@ -259,7 +259,7 @@ private List format(final List argList) { } } if (!isComment) { - Pair mlComments = sqlDialect.getMultiLineComments(); + Pair mlComments = SQL_DIALECT.getMultiLineComments(); if (token.getString().startsWith(mlComments.getFirst())) { index += insertReturnAndIndent(argList, index + 1, indent); } @@ -385,7 +385,7 @@ private boolean isJoinStart(List argList, int index) { } private boolean isFunction(String name) { - return sqlDialect.getKeywordType(name) == DBPKeywordType.FUNCTION; + return SQL_DIALECT.getKeywordType(name) == DBPKeywordType.FUNCTION; } private static String getDefaultLineSeparator() { @@ -406,7 +406,7 @@ private int insertReturnAndIndent(final List argList, final int final FormatterToken token = argList.get(argIndex); final FormatterToken prevToken = argList.get(argIndex - 1); if (token.getType() == TokenType.COMMENT - && isCommentLine(sqlDialect, token.getString()) + && isCommentLine(SQL_DIALECT, token.getString()) && prevToken.getType() != TokenType.END) { s.setCharAt(0, ' '); s.setLength(1); 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 f80b084c91..53e1bfd443 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 @@ -31,8 +31,8 @@ */ class SQLTokensParser { - private static final String[] twoCharacterSymbol = {"<>", "<=", ">=", "||", "()", "!=", ":=", ".*"}; - private static final SQLDialect sqlDialect = SQLDialect.INSTANCE; + private static final String[] TWO_CHARACTER_SYMBOL = {"<>", "<=", ">=", "||", "()", "!=", ":=", ".*"}; + private static final SQLDialect SQL_DIALECT = SQLDialect.INSTANCE; private final String[][] quoteStrings; private final char structSeparator; @@ -44,10 +44,10 @@ class SQLTokensParser { private int fPos; SQLTokensParser() { - this.structSeparator = sqlDialect.getStructSeparator(); - this.catalogSeparator = sqlDialect.getCatalogSeparator(); - this.quoteStrings = sqlDialect.getIdentifierQuoteStrings(); - this.singleLineComments = sqlDialect.getSingleLineComments(); + this.structSeparator = SQL_DIALECT.getStructSeparator(); + this.catalogSeparator = SQL_DIALECT.getCatalogSeparator(); + this.quoteStrings = SQL_DIALECT.getIdentifierQuoteStrings(); + this.singleLineComments = SQL_DIALECT.getSingleLineComments(); this.singleLineCommentStart = new char[this.singleLineComments.length]; for (int i = 0; i < singleLineComments.length; i++) { if (singleLineComments[i].isEmpty()) { @@ -188,7 +188,7 @@ else if (contains(singleLineCommentStart, fChar)) { } return new FormatterToken(TokenType.COMMAND, word + s.toString(), start_pos); } - if (sqlDialect.getKeywordType(word) != null) { + if (SQL_DIALECT.getKeywordType(word) != null) { return new FormatterToken(TokenType.KEYWORD, word, start_pos); } return new FormatterToken(TokenType.NAME, word, start_pos); @@ -250,7 +250,7 @@ else if (isSymbol(fChar)) { return new FormatterToken(TokenType.SYMBOL, s.toString(), start_pos); } char ch2 = fBefore.charAt(fPos); - for (String aTwoCharacterSymbol : twoCharacterSymbol) { + for (String aTwoCharacterSymbol : TWO_CHARACTER_SYMBOL) { if (aTwoCharacterSymbol.charAt(0) == fChar && aTwoCharacterSymbol.charAt(1) == ch2) { fPos++; s.append(ch2); diff --git a/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java b/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java index 53a186169f..bee6b9c70a 100644 --- a/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java +++ b/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java @@ -33,7 +33,7 @@ import sortpom.parameter.PluginParameters; public class SortPomFormatterFunc implements FormatterFunc { - private static final Logger logger = LoggerFactory.getLogger(SortPomFormatterFunc.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SortPomFormatterFunc.class); private final SortPomCfg cfg; public SortPomFormatterFunc(SortPomCfg cfg) { @@ -101,19 +101,19 @@ public MySortPomLogger(boolean quiet) { @Override public void warn(String content) { - logger.warn(content); + LOGGER.warn(content); } @Override public void info(String content) { if (!quiet) { - logger.info(content); + LOGGER.info(content); } } @Override public void error(String content) { - logger.error(content); + LOGGER.error(content); } } } 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 777223c5f7..4011bf6d6c 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 @@ -83,7 +83,7 @@ /** Adds a {@code spotless{Name}Check} and {@code spotless{Name}Apply} task. */ public class FormatExtension { - private static final Logger logger = LoggerFactory.getLogger(FormatExtension.class); + private static final Logger LOGGER = LoggerFactory.getLogger(FormatExtension.class); final SpotlessExtension spotless; final List> lazyActions = new ArrayList<>(); @@ -548,7 +548,7 @@ public void indentWithTabs() { } private static void logDeprecation(String methodName, String replacement) { - logger.warn("'{}' is deprecated, use '{}' in your gradle build script instead.", methodName, replacement); + LOGGER.warn("'{}' is deprecated, use '{}' in your gradle build script instead.", methodName, replacement); } /** Ensures formatting of files via native binary. */ 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 d6b6369bf8..b8260e3b9c 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 @@ -142,7 +142,7 @@ private static Provisioner forConfigurationContainer(Project project, Configurat }; } - private static final Logger logger = LoggerFactory.getLogger(GradleProvisioner.class); + private static final Logger LOGGER = LoggerFactory.getLogger(GradleProvisioner.class); /** Models a request to the provisioner. */ private static class Request { diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/kotlin/Ktlint.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/kotlin/Ktlint.java index a54e0d9764..c0c193d2c3 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/kotlin/Ktlint.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/kotlin/Ktlint.java @@ -31,7 +31,7 @@ import com.diffplug.spotless.maven.FormatterStepFactory; public class Ktlint implements FormatterStepFactory { - private static final File defaultEditorConfig = new File(".editorconfig"); + private static final File DEFAULT_EDITOR_CONFIG = new File(".editorconfig"); @Parameter private String version; @@ -46,8 +46,8 @@ public class Ktlint implements FormatterStepFactory { public FormatterStep newFormatterStep(final FormatterStepConfig stepConfig) { String ktlintVersion = version != null ? version : KtLintStep.defaultVersion(); FileSignature configPath = null; - if (editorConfigPath == null && defaultEditorConfig.exists()) { - editorConfigPath = defaultEditorConfig.getPath(); + if (editorConfigPath == null && DEFAULT_EDITOR_CONFIG.exists()) { + editorConfigPath = DEFAULT_EDITOR_CONFIG.getPath(); } if (editorConfigPath != null) { configPath = ThrowingEx.get(() -> FileSignature.signAsList(stepConfig.getFileLocator().locateFile(editorConfigPath))); diff --git a/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java b/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java index 672dd8eba9..c75d618ac0 100644 --- a/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java +++ b/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java @@ -140,22 +140,22 @@ private static Provisioner caching(String name, Supplier input) { /** Creates a Provisioner for the mavenCentral repo. */ public static Provisioner mavenCentral() { - return mavenCentral.get(); + return MAVEN_CENTRAL.get(); } - private static final Supplier mavenCentral = Suppliers.memoize(() -> caching("mavenCentral", () -> createWithRepositories(repo -> repo.mavenCentral()))); + private static final Supplier MAVEN_CENTRAL = Suppliers.memoize(() -> caching("mavenCentral", () -> createWithRepositories(repo -> repo.mavenCentral()))); /** Creates a Provisioner for the local maven repo for development purpose. */ public static Provisioner mavenLocal() { - return mavenLocal.get(); + return MAVEN_LOCAL.get(); } - private static final Supplier mavenLocal = () -> createWithRepositories(repo -> repo.mavenLocal()); + private static final Supplier MAVEN_LOCAL = () -> createWithRepositories(repo -> repo.mavenLocal()); /** Creates a Provisioner for the Sonatype snapshots maven repo for development purpose. */ public static Provisioner snapshots() { - return snapshots.get(); + 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/FileSignatureTest.java b/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java index 88e4175046..98db00c09e 100644 --- a/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java @@ -31,24 +31,24 @@ import org.junit.jupiter.api.condition.EnabledOnOs; class FileSignatureTest extends ResourceHarness { - private static final String[] inputPaths = {"A", "C", "C", "A", "B"}; - private static final String[] expectedPathList = inputPaths; - private static final String[] expectedPathSet = {"A", "B", "C"}; + private static final String[] INPUT_PATHS = {"A", "C", "C", "A", "B"}; + private static final String[] EXPECTED_PATH_LIST = INPUT_PATHS; + private static final String[] EXPECTED_PATH_SET = {"A", "B", "C"}; @Test void testFromList() throws IOException { - Collection inputFiles = getTestFiles(inputPaths); + Collection inputFiles = getTestFiles(INPUT_PATHS); FileSignature signature = FileSignature.signAsList(inputFiles); - Collection expectedFiles = getTestFiles(expectedPathList); + Collection expectedFiles = getTestFiles(EXPECTED_PATH_LIST); Collection outputFiles = signature.files(); assertThat(outputFiles).containsExactlyElementsOf(expectedFiles); } @Test void testFromSet() throws IOException { - Collection inputFiles = getTestFiles(inputPaths); + Collection inputFiles = getTestFiles(INPUT_PATHS); FileSignature signature = FileSignature.signAsSet(inputFiles); - Collection expectedFiles = getTestFiles(expectedPathSet); + Collection expectedFiles = getTestFiles(EXPECTED_PATH_SET); Collection outputFiles = signature.files(); assertThat(outputFiles).containsExactlyElementsOf(expectedFiles); } @@ -63,7 +63,7 @@ void testFromDirectory() { @Test void testFromFilesAndDirectory() throws IOException { File dir = new File(rootFolder(), "dir"); - List files = getTestFiles(inputPaths); + List files = getTestFiles(INPUT_PATHS); files.add(dir); Collections.shuffle(files); assertThatThrownBy(() -> FileSignature.signAsList(files)) diff --git a/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java b/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java index 6bc131cbc3..e580429bb7 100644 --- a/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java @@ -33,7 +33,7 @@ class LicenseHeaderStepTest extends ResourceHarness { private static final String FILE_NO_LICENSE = "license/FileWithoutLicenseHeader.test"; - private static final String package_ = LicenseHeaderStep.DEFAULT_JAVA_HEADER_DELIMITER; + private static final String PACKAGE_ = LicenseHeaderStep.DEFAULT_JAVA_HEADER_DELIMITER; private static final String HEADER_WITH_$YEAR = "This is a fake license, $YEAR. ACME corp."; private static final String HEADER_WITH_RANGE_TO_$YEAR = "This is a fake license with range, 2009-$YEAR. ACME corp."; private static final String HEADER_WITH_$FILE = "This is a fake license, $FILE. ACME corp."; @@ -41,7 +41,7 @@ class LicenseHeaderStepTest extends ResourceHarness { @Test void parseExistingYear() throws Exception { - StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR), package_).build()) + StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR), PACKAGE_).build()) // has existing .test(hasHeader("This is a fake license, 2007. ACME corp."), hasHeader("This is a fake license, 2007. ACME corp.")) // if prefix changes, the year will get set to today @@ -52,14 +52,14 @@ void parseExistingYear() throws Exception { @Test void fromHeader() throws Throwable { - FormatterStep step = LicenseHeaderStep.headerDelimiter(getTestResource("license/TestLicense"), package_).build(); + FormatterStep step = LicenseHeaderStep.headerDelimiter(getTestResource("license/TestLicense"), PACKAGE_).build(); StepHarness.forStep(step) .testResource("license/MissingLicense.test", "license/HasLicense.test"); } @Test void should_apply_license_containing_YEAR_token() throws Throwable { - StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR), package_).build()) + StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR), PACKAGE_).build()) .test(getTestResource(FILE_NO_LICENSE), hasHeaderYear(currentYear())) .testUnaffected(hasHeaderYear(currentYear())) .testUnaffected(hasHeaderYear("2003")) @@ -69,7 +69,7 @@ void should_apply_license_containing_YEAR_token() throws Throwable { .test(hasHeaderYear("not a year"), hasHeaderYear(currentYear())); // Check with variant String otherFakeLicense = "This is a fake license. Copyright $YEAR ACME corp."; - StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(otherFakeLicense), package_).build()) + StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(otherFakeLicense), PACKAGE_).build()) .test(getTestResource(FILE_NO_LICENSE), hasHeaderYear(otherFakeLicense, currentYear())) .testUnaffected(hasHeaderYear(otherFakeLicense, currentYear())) .test(hasHeader("This is a fake license. Copyright "), hasHeaderYear(otherFakeLicense, currentYear())) @@ -79,13 +79,13 @@ void should_apply_license_containing_YEAR_token() throws Throwable { //Check when token is of the format $today.year String HEADER_WITH_YEAR_INTELLIJ = "This is a fake license, $today.year. ACME corp."; - StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_YEAR_INTELLIJ), package_).build()) + StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_YEAR_INTELLIJ), PACKAGE_).build()) .test(hasHeader(HEADER_WITH_YEAR_INTELLIJ), hasHeader(HEADER_WITH_YEAR_INTELLIJ.replace("$today.year", currentYear()))); } @Test void updateYearWithLatest() throws Throwable { - FormatterStep step = LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR), package_) + FormatterStep step = LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR), PACKAGE_) .withYearMode(YearMode.UPDATE_TO_TODAY) .build(); StepHarness.forStep(step) @@ -96,21 +96,21 @@ void updateYearWithLatest() throws Throwable { @Test void should_apply_license_containing_YEAR_token_with_non_default_year_separator() throws Throwable { - StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR), package_).withYearSeparator(", ").build()) + StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR), PACKAGE_).withYearSeparator(", ").build()) .testUnaffected(hasHeaderYear("1990, 2015")) .test(hasHeaderYear("1990-2015"), hasHeaderYear("1990, 2015")); } @Test void should_apply_license_containing_YEAR_token_with_special_character_in_year_separator() throws Throwable { - StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR), package_).withYearSeparator("(").build()) + StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR), PACKAGE_).withYearSeparator("(").build()) .testUnaffected(hasHeaderYear("1990(2015")) .test(hasHeaderYear("1990-2015"), hasHeaderYear("1990(2015")); } @Test void should_apply_license_containing_YEAR_token_with_custom_separator() throws Throwable { - StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR), package_).build()) + StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR), PACKAGE_).build()) .test(getTestResource(FILE_NO_LICENSE), hasHeaderYear(currentYear())) .testUnaffected(hasHeaderYear(currentYear())) .testUnaffected(hasHeaderYear("2003")) @@ -120,7 +120,7 @@ void should_apply_license_containing_YEAR_token_with_custom_separator() throws T @Test void should_remove_header_when_empty() throws Throwable { - StepHarness.forStep(LicenseHeaderStep.headerDelimiter("", package_).build()) + StepHarness.forStep(LicenseHeaderStep.headerDelimiter("", PACKAGE_).build()) .testUnaffected(getTestResource("license/MissingLicense.test")) .test(getTestResource("license/HasLicense.test"), getTestResource("license/MissingLicense.test")); } @@ -244,14 +244,14 @@ protected FormatterStep create() { @Test void should_apply_license_containing_YEAR_token_in_range() throws Throwable { - FormatterStep step = LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_RANGE_TO_$YEAR), package_).withYearMode(YearMode.UPDATE_TO_TODAY).build(); + FormatterStep step = LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_RANGE_TO_$YEAR), PACKAGE_).withYearMode(YearMode.UPDATE_TO_TODAY).build(); StepHarness.forStep(step).test(hasHeaderWithRangeAndWithYearTo("2015"), hasHeaderWithRangeAndWithYearTo(currentYear())); } @Test void should_update_year_for_license_with_address() throws Throwable { int currentYear = LocalDate.now(ZoneOffset.UTC).getYear(); - FormatterStep step = LicenseHeaderStep.headerDelimiter(header(licenceWithAddress()), package_).withYearMode(YearMode.UPDATE_TO_TODAY).build(); + FormatterStep step = LicenseHeaderStep.headerDelimiter(header(licenceWithAddress()), PACKAGE_).withYearMode(YearMode.UPDATE_TO_TODAY).build(); StepHarness.forStep(step).test( hasHeader(licenceWithAddress().replace("$YEAR", "2015")), hasHeader(licenceWithAddress().replace("$YEAR", "2015-" + currentYear))); @@ -259,7 +259,7 @@ void should_update_year_for_license_with_address() throws Throwable { @Test void should_preserve_year_for_license_with_address() throws Throwable { - FormatterStep step = LicenseHeaderStep.headerDelimiter(header(licenceWithAddress()), package_).withYearMode(YearMode.PRESERVE).build(); + FormatterStep step = LicenseHeaderStep.headerDelimiter(header(licenceWithAddress()), PACKAGE_).withYearMode(YearMode.PRESERVE).build(); StepHarness.forStep(step).test( hasHeader(licenceWithAddress().replace("$YEAR", "2015").replace("FooBar Inc. All", "FooBar Inc. All")), hasHeader(licenceWithAddress().replace("$YEAR", "2015"))); @@ -267,7 +267,7 @@ void should_preserve_year_for_license_with_address() throws Throwable { @Test void should_apply_license_containing_filename_token() throws Exception { - FormatterStep step = LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$FILE), package_).build(); + FormatterStep step = LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$FILE), PACKAGE_).build(); StepHarnessWithFile.forStep(this, step) .test("Test.java", getTestResource(FILE_NO_LICENSE), hasHeaderFileName(HEADER_WITH_$FILE, "Test.java")) .testUnaffected(new File("Test.java"), hasHeaderFileName(HEADER_WITH_$FILE, "Test.java")); @@ -275,7 +275,7 @@ void should_apply_license_containing_filename_token() throws Exception { @Test void should_update_license_containing_filename_token() throws Exception { - FormatterStep step = LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$FILE), package_).build(); + FormatterStep step = LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$FILE), PACKAGE_).build(); StepHarnessWithFile.forStep(this, step) .test("After.java", hasHeaderFileName(HEADER_WITH_$FILE, "Before.java"), @@ -284,7 +284,7 @@ void should_update_license_containing_filename_token() throws Exception { @Test void should_apply_license_containing_YEAR_filename_token() throws Exception { - FormatterStep step = LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR_$FILE), package_).build(); + FormatterStep step = LicenseHeaderStep.headerDelimiter(header(HEADER_WITH_$YEAR_$FILE), PACKAGE_).build(); StepHarnessWithFile.forStep(this, step) .test("Test.java", getTestResource(FILE_NO_LICENSE), @@ -295,7 +295,7 @@ void should_apply_license_containing_YEAR_filename_token() throws Exception { void noPackage() throws Throwable { String header = header(getTestResource("license/TestLicense")); - FormatterStep step = LicenseHeaderStep.headerDelimiter(header, package_).build(); + FormatterStep step = LicenseHeaderStep.headerDelimiter(header, PACKAGE_).build(); StepHarness.forStep(step) .test(ResourceHarness.getTestResource("license/HelloWorld_java.test"), header + ResourceHarness.getTestResource("license/HelloWorld_java.test")) .test(ResourceHarness.getTestResource("license/HelloWorld_withImport_java.test"), header + ResourceHarness.getTestResource("license/HelloWorld_withImport_java.test")); @@ -305,7 +305,7 @@ void noPackage() throws Throwable { @Test void moduleInfo() throws Throwable { String header = header(getTestResource("license/TestLicense")); - FormatterStep step = LicenseHeaderStep.headerDelimiter(header, package_).build(); + FormatterStep step = LicenseHeaderStep.headerDelimiter(header, PACKAGE_).build(); StepHarness.forStep(step) .test(ResourceHarness.getTestResource("license/module-info.test"), header + ResourceHarness.getTestResource("license/module-info.test")); } diff --git a/testlib/src/test/java/com/diffplug/spotless/markdown/FlexmarkStepTest.java b/testlib/src/test/java/com/diffplug/spotless/markdown/FlexmarkStepTest.java index 0406c05678..a6640e33c5 100644 --- a/testlib/src/test/java/com/diffplug/spotless/markdown/FlexmarkStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/markdown/FlexmarkStepTest.java @@ -21,11 +21,11 @@ import com.diffplug.spotless.TestProvisioner; class FlexmarkStepTest { - private static final String oldestSupported = "0.62.2"; + private static final String OLDEST_SUPPORTED = "0.62.2"; @Test void behaviorOldest() { - StepHarness.forStep(FlexmarkStep.create(oldestSupported, TestProvisioner.mavenCentral())) + StepHarness.forStep(FlexmarkStep.create(OLDEST_SUPPORTED, TestProvisioner.mavenCentral())) .testResource( "markdown/flexmark/FlexmarkUnformatted.md", "markdown/flexmark/FlexmarkFormatted.md");