From 958864d1f3089421de05dd551cdf8fb117e7ae33 Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Mon, 20 Feb 2023 11:10:04 +0400 Subject: [PATCH 1/3] Add cleanthat to spotless config --- gradle/spotless.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/gradle/spotless.gradle b/gradle/spotless.gradle index 677630ac69..67d0c65ceb 100644 --- a/gradle/spotless.gradle +++ b/gradle/spotless.gradle @@ -17,6 +17,7 @@ spotless { java { ratchetFrom 'origin/main' bumpThisNumberIfACustomStepChanges(1) + cleanthat().version("2.4").sourceCompatibility("11").clearMutators().addMutators(['RSPEC-6212']) licenseHeaderFile rootProject.file('gradle/spotless.license') importOrderFile rootProject.file('gradle/spotless.importorder') eclipse().configFile rootProject.file('gradle/spotless.eclipseformat.xml') From 53f3fcfbef89e12294be8b1210426294654c6790 Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Tue, 7 Mar 2023 10:41:24 +0400 Subject: [PATCH 2/3] Improve gradle configuration --- gradle/spotless.gradle | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/gradle/spotless.gradle b/gradle/spotless.gradle index 67d0c65ceb..587a0b40a7 100644 --- a/gradle/spotless.gradle +++ b/gradle/spotless.gradle @@ -17,7 +17,10 @@ spotless { java { ratchetFrom 'origin/main' bumpThisNumberIfACustomStepChanges(1) - cleanthat().version("2.4").sourceCompatibility("11").clearMutators().addMutators(['RSPEC-6212']) + // `setMutators` will discard default mutators + // https://sonarsource.atlassian.net/browse/RSPEC-6212 + cleanthat().version("2.9").sourceCompatibility(project.sourceCompatibility.toString()).clearMutators() + .addMutator('RSPEC-6212') licenseHeaderFile rootProject.file('gradle/spotless.license') importOrderFile rootProject.file('gradle/spotless.importorder') eclipse().configFile rootProject.file('gradle/spotless.eclipseformat.xml') From 2fdba8fed64e7c00504d9dda9897ec15cd2f4708 Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Thu, 30 Mar 2023 09:01:29 +0400 Subject: [PATCH 3/3] Apply RSPEC-6112 over the whole repository --- .../eclipse/base/osgi/BundleController.java | 2 +- .../eclipse/base/osgi/ResourceAccessor.java | 10 +-- .../eclipse/base/osgi/ServiceCollection.java | 2 +- .../eclipse/base/runtime/PluginRegistrar.java | 2 +- .../base/service/SingleSlf4JService.java | 2 +- .../base/service/TemporaryLocation.java | 6 +- .../base/SpotlessEclipseFrameworkTest.java | 2 +- .../eclipse/base/osgi/BundleSetTest.java | 6 +- .../base/osgi/ServiceCollectionTest.java | 8 +- .../wtp/EclipseHtmlFormatterStepImpl.java | 2 +- .../wtp/html/StructuredDocumentProcessor.java | 6 +- .../eclipse/wtp/sse/PluginPreferences.java | 6 +- .../wtp/EclipseCssFormatterStepImplTest.java | 2 +- .../wtp/EclipseHtmlFormatterStepImplTest.java | 4 +- .../wtp/EclipseJsFormatterStepImplTest.java | 2 +- .../wtp/EclipseJsonFormatterStepImplTest.java | 2 +- ...ormatterStepImplAllowExternalURIsTest.java | 2 +- ...XmlFormatterStepImplCatalogLookupTest.java | 2 +- .../wtp/EclipseXmlFormatterStepImplTest.java | 2 +- .../spotless/extra/eclipse/wtp/TestData.java | 12 +-- .../groovy/GrEclipseFormatterStepImpl.java | 8 +- .../extra/EclipseBasedStepBuilder.java | 22 +++--- .../spotless/extra/EquoBasedStepBuilder.java | 4 +- .../extra/GitAttributesLineEndings.java | 22 +++--- .../diffplug/spotless/extra/GitRatchet.java | 10 +-- .../spotless/extra/GitWorkarounds.java | 6 +- .../extra/cpp/EclipseCdtFormatterStep.java | 4 +- .../extra/groovy/GrEclipseFormatterStep.java | 4 +- .../integration/DiffMessageFormatter.java | 20 ++--- .../extra/wtp/EclipseWtpFormatterStep.java | 11 ++- .../spotless/extra/GitAttributesTest.java | 2 +- .../extra/GitRachetMergeBaseTest.java | 6 +- .../extra/eclipse/EclipseResourceHarness.java | 4 +- .../extra/eclipse/EquoResourceHarness.java | 2 +- .../wtp/EclipseWtpFormatterStepTest.java | 10 +-- .../java/JavaCleanthatRefactorerFunc.java | 2 +- .../compat/KtLintCompat0Dot46Dot0Adapter.java | 2 +- .../compat/KtLintCompat0Dot47Dot0Adapter.java | 2 +- .../compat/KtLintCompat0Dot48Dot0Adapter.java | 10 +-- .../glue/diktat/DiktatFormatterFunc.java | 4 +- .../spotless/glue/gson/GsonFormatterFunc.java | 2 +- .../glue/yaml/JacksonYamlFormatterFunc.java | 2 +- .../glue/ktlint/KtlintFormatterFunc.java | 2 +- .../diffplug/spotless/EncodingErrorMsg.java | 26 +++---- .../diffplug/spotless/FeatureClassLoader.java | 11 ++- .../com/diffplug/spotless/FileSignature.java | 16 ++-- .../FilterByContentPatternFormatterStep.java | 7 +- .../spotless/FilterByFileFormatterStep.java | 4 +- .../com/diffplug/spotless/ForeignExe.java | 8 +- .../java/com/diffplug/spotless/Formatter.java | 26 +++---- .../spotless/FormatterProperties.java | 35 +++++---- .../main/java/com/diffplug/spotless/Jvm.java | 41 +++++----- .../spotless/LazyForwardingEquality.java | 6 +- .../com/diffplug/spotless/LineEnding.java | 9 +-- .../com/diffplug/spotless/MoreIterables.java | 6 +- .../java/com/diffplug/spotless/NoLambda.java | 4 +- .../com/diffplug/spotless/PaddedCell.java | 16 ++-- .../com/diffplug/spotless/ProcessRunner.java | 16 ++-- .../RingBufferByteArrayOutputStream.java | 6 +- .../spotless/SerializableFileFilterImpl.java | 4 +- .../com/diffplug/spotless/SpotlessCache.java | 2 +- .../com/diffplug/spotless/ThrowingEx.java | 4 +- .../spotless/antlr4/Antlr4FormatterStep.java | 5 +- .../spotless/cpp/ClangFormatStep.java | 6 +- .../spotless/generic/EndWithNewlineStep.java | 6 +- .../diffplug/spotless/generic/IndentStep.java | 14 ++-- .../diffplug/spotless/generic/Jsr223Step.java | 5 +- .../spotless/generic/LicenseHeaderStep.java | 75 +++++++++---------- .../spotless/generic/PipeStepPair.java | 19 +++-- .../spotless/java/FormatAnnotationsStep.java | 17 ++--- .../spotless/java/ImportOrderStep.java | 8 +- .../diffplug/spotless/java/ImportSorter.java | 32 ++++---- .../spotless/java/ImportSorterImpl.java | 42 +++++------ .../diffplug/spotless/java/ModuleHelper.java | 19 +++-- .../diffplug/spotless/kotlin/BadSemver.java | 11 ++- .../diffplug/spotless/kotlin/KtfmtStep.java | 9 +-- .../spotless/markdown/FreshMarkStep.java | 3 +- .../markdown/LibMarkdownPreconditions.java | 4 +- .../spotless/npm/EslintFormatterStep.java | 2 +- .../com/diffplug/spotless/npm/FileFinder.java | 4 +- .../diffplug/spotless/npm/JsonEscaper.java | 8 +- .../spotless/npm/NodeExecutableResolver.java | 4 +- .../NodeModulesCachingNpmProcessFactory.java | 2 +- .../spotless/npm/NodeServerLayout.java | 7 +- .../spotless/npm/NpmExecutableResolver.java | 4 +- .../npm/NpmFormatterStepStateBase.java | 8 +- .../spotless/npm/NpmPathResolver.java | 6 +- .../spotless/npm/NpmResourceHelper.java | 19 +++-- .../diffplug/spotless/npm/PlatformInfo.java | 10 +-- .../spotless/npm/PrettierFormatterStep.java | 8 +- .../npm/PrettierMissingParserException.java | 2 +- .../com/diffplug/spotless/npm/ShadowCopy.java | 4 +- .../spotless/npm/SimpleJsonWriter.java | 4 +- .../spotless/npm/SimpleRestClient.java | 15 ++-- .../diffplug/spotless/npm/TimedLogger.java | 18 ++--- .../spotless/npm/TsFmtFormatterStep.java | 2 +- .../diffplug/spotless/python/BlackStep.java | 4 +- .../diffplug/spotless/scala/ScalaFmtStep.java | 2 +- .../DBeaverSQLFormatterConfiguration.java | 12 +-- .../spotless/sql/dbeaver/FormatterToken.java | 4 +- .../sql/dbeaver/SQLTokenizedFormatter.java | 32 ++++---- .../spotless/sql/dbeaver/SQLTokensParser.java | 30 ++++---- .../pjf/PalantirJavaFormatFormatterFunc.java | 4 +- .../glue/scalafmt/ScalafmtFormatterFunc.java | 4 +- .../glue/pom/SortPomFormatterFunc.java | 4 +- .../RingBufferByteArrayOutputStreamTest.java | 12 +-- .../spotless/npm/TimedLoggerTest.java | 2 +- .../KtLintCompat0Dot48Dot0AdapterTest.java | 11 ++- .../gradle/spotless/FormatExtension.java | 22 +++--- .../gradle/spotless/GradleProvisioner.java | 8 +- .../com/diffplug/gradle/spotless/IdeHook.java | 6 +- .../gradle/spotless/JavascriptExtension.java | 2 +- .../gradle/spotless/JvmLocalCache.java | 6 +- .../gradle/spotless/SerializableMisc.java | 8 +- .../gradle/spotless/SpotlessDiagnoseTask.java | 8 +- .../gradle/spotless/SpotlessExtension.java | 2 +- .../spotless/SpotlessPluginRedirect.java | 9 +-- .../gradle/spotless/SpotlessTaskImpl.java | 7 +- .../gradle/spotless/TypescriptExtension.java | 4 +- .../gradle/spotless/Antlr4ExtensionTest.java | 8 +- .../spotless/DiffMessageFormatterTest.java | 38 +++++----- .../spotless/ErrorShouldRethrowTest.java | 10 +-- .../gradle/spotless/FileTreeTest.java | 6 +- .../gradle/spotless/FormatTaskTest.java | 6 +- .../GradleIncrementalResolutionTest.java | 18 ++--- .../spotless/GradleIntegrationHarness.java | 6 +- .../gradle/spotless/GroovyExtensionTest.java | 4 +- .../spotless/GroovyGradleExtensionTest.java | 4 +- .../diffplug/gradle/spotless/IdeHookTest.java | 6 +- .../spotless/JavascriptExtensionTest.java | 4 +- .../gradle/spotless/LicenseHeaderTest.java | 4 +- .../gradle/spotless/MultiProjectTest.java | 4 +- .../NpmInstallCacheIntegrationTests.java | 26 +++---- .../gradle/spotless/PaddedCellTaskTest.java | 24 +++--- .../gradle/spotless/SpotlessTaskImplTest.java | 5 +- .../spotless/maven/AbstractSpotlessMojo.java | 2 +- .../diffplug/spotless/maven/FileLocator.java | 10 +-- .../spotless/maven/FormatterFactory.java | 2 +- .../spotless/maven/GitRatchetMaven.java | 5 +- .../spotless/maven/incremental/FileIndex.java | 24 +++--- .../maven/incremental/IndexBasedChecker.java | 4 +- .../incremental/ObjectDigestOutputStream.java | 4 +- .../maven/incremental/PluginFingerprint.java | 4 +- .../maven/incremental/UpToDateChecking.java | 2 +- .../diffplug/spotless/maven/java/Java.java | 2 +- .../diffplug/spotless/maven/json/Gson.java | 2 +- .../diffplug/spotless/maven/json/Simple.java | 2 +- .../spotless/maven/FileLocatorTest.java | 8 +- .../spotless/maven/IncludesExcludesTest.java | 46 ++++++------ .../maven/MavenIntegrationHarness.java | 11 ++- .../spotless/maven/MavenProvisionerTest.java | 4 +- .../diffplug/spotless/maven/MavenRunner.java | 4 +- .../maven/MultiModuleProjectTest.java | 4 +- .../spotless/maven/MultipleFormatsTest.java | 12 +-- .../spotless/maven/SpecificFilesTest.java | 4 +- .../maven/antlr4/Antlr4FormatterTest.java | 4 +- .../maven/generic/EclipseWtpTest.java | 6 +- .../maven/generic/EndWithNewlineTest.java | 6 +- .../spotless/maven/generic/IndentTest.java | 4 +- .../spotless/maven/generic/Jsr223Test.java | 4 +- .../maven/generic/LicenseHeaderTest.java | 16 ++-- .../maven/generic/LineEndingsTest.java | 4 +- .../spotless/maven/generic/NativeCmdTest.java | 4 +- .../maven/generic/ReplaceRegexTest.java | 4 +- .../spotless/maven/generic/ReplaceTest.java | 4 +- .../generic/TrimTrailingWhitespaceTest.java | 8 +- .../spotless/maven/groovy/GrEclipseTest.java | 10 +-- .../maven/groovy/ImportOrderTest.java | 4 +- .../maven/incremental/FileIndexHarness.java | 8 +- .../maven/incremental/FileIndexTest.java | 12 +-- .../incremental/IndexBasedCheckerTest.java | 9 +-- .../maven/incremental/NoopCheckerTest.java | 6 +- .../incremental/PluginFingerprintTest.java | 2 +- .../incremental/UpToDateCheckingTest.java | 48 ++++++------ .../java/CleanthatJavaRefactorerTest.java | 2 +- .../maven/java/EclipseFormatStepTest.java | 4 +- .../maven/java/FormatAnnotationsStepTest.java | 6 +- .../maven/java/GoogleJavaFormatTest.java | 2 +- .../spotless/maven/java/ImportOrderTest.java | 4 +- .../maven/java/PalantirJavaFormatTest.java | 2 +- .../java/RemoveUnusedImportsStepTest.java | 4 +- .../javascript/JavascriptFormatStepTest.java | 6 +- .../spotless/maven/kotlin/DiktatTest.java | 10 +-- .../spotless/maven/kotlin/KtfmtTest.java | 4 +- .../spotless/maven/kotlin/KtlintTest.java | 6 +- .../npm/NpmStepsWithNpmInstallCacheTest.java | 16 ++-- ...namicallyInstalledNpmInstallationTest.java | 8 +- .../prettier/PrettierFormatStepTest.java | 20 ++--- .../spotless/maven/scala/ScalafmtTest.java | 4 +- .../typescript/TypescriptFormatStepTest.java | 4 +- .../com/diffplug/spotless/ReflectionUtil.java | 4 +- .../diffplug/spotless/ResourceHarness.java | 16 ++-- .../spotless/SerializableEqualityTester.java | 8 +- .../com/diffplug/spotless/StepHarness.java | 2 +- .../spotless/StepHarnessWithFile.java | 2 +- .../diffplug/spotless/TestProvisioner.java | 16 ++-- .../spotless/EncodingErrorMsgTest.java | 14 ++-- .../diffplug/spotless/FileSignatureTest.java | 6 +- .../spotless/FormatterPropertiesTest.java | 18 ++--- .../com/diffplug/spotless/FormatterTest.java | 6 +- .../java/com/diffplug/spotless/JvmTest.java | 6 +- .../com/diffplug/spotless/PaddedCellTest.java | 6 +- .../spotless/cpp/ClangFormatStepTest.java | 4 +- .../spotless/cpp/CppDefaultsTest.java | 6 +- .../spotless/generic/IndentStepTest.java | 2 +- .../generic/LicenseHeaderStepTest.java | 12 +-- .../spotless/json/JacksonJsonStepTest.java | 4 +- .../json/JsonFormatterStepCommonTests.java | 12 +-- .../spotless/json/JsonSimpleStepTest.java | 12 +-- .../spotless/kotlin/DiktatStepTest.java | 2 +- .../spotless/npm/EslintFormatterStepTest.java | 26 +++---- .../npm/PrettierFormatterStepTest.java | 22 +++--- .../diffplug/spotless/npm/ShadowCopyTest.java | 32 ++++---- .../spotless/npm/TsFmtFormatterStepTest.java | 12 +-- 214 files changed, 956 insertions(+), 983 deletions(-) diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleController.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleController.java index 3589bd7082..f8be82edc4 100644 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleController.java +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleController.java @@ -168,7 +168,7 @@ public Bundle getBundle(String location) { @Override public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException { //Filters are based on class names - String interfaceClassName = (null == clazz) ? filter : clazz; + var interfaceClassName = (null == clazz) ? filter : clazz; return services.getReferences(interfaceClassName); } diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ResourceAccessor.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ResourceAccessor.java index b75a2835ac..da64984628 100644 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ResourceAccessor.java +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ResourceAccessor.java @@ -63,7 +63,7 @@ class ResourceAccessor { /** Resources are located in the JAR of the given class * @throws BundleException */ ResourceAccessor(Class clazz) throws BundleException { - String bundleObjPath = clazz.getName(); + var bundleObjPath = clazz.getName(); fatJarResourcePath = bundleObjPath.substring(0, bundleObjPath.lastIndexOf('.')); try { bundleFile = getBundlFile(clazz); @@ -74,7 +74,7 @@ class ResourceAccessor { private static BundleFile getBundlFile(Class clazz) throws BundleException { URI objUri = getBundleUri(clazz); - File jarOrDirectory = new File(objUri.getPath()); + var jarOrDirectory = new File(objUri.getPath()); if (!(jarOrDirectory.exists() && jarOrDirectory.canRead())) { throw new BundleException(String.format("Path '%s' for '%s' is not accessible exist on local file system.", objUri, clazz.getName()), BundleException.READ_ERROR); } @@ -87,7 +87,7 @@ private static BundleFile getBundlFile(Class clazz) throws BundleException { private static URI getBundleUri(Class clazz) throws BundleException { try { - URL objUrl = clazz.getProtectionDomain().getCodeSource().getLocation(); + var objUrl = clazz.getProtectionDomain().getCodeSource().getLocation(); return objUrl.toURI(); } catch (NullPointerException e) { //No bunlde should be used for RT classes lookup. See also org.eclipse.core.runtime.PerformanceStats. @@ -101,10 +101,10 @@ private static URI getBundleUri(Class clazz) throws BundleException { /** Get the manifest name from the resources. */ String getManifestName() throws BundleException { - URL manifestUrl = getEntry(JarFile.MANIFEST_NAME); + var manifestUrl = getEntry(JarFile.MANIFEST_NAME); if (null != manifestUrl) { try { - Manifest manifest = new Manifest(manifestUrl.openStream()); + var manifest = new Manifest(manifestUrl.openStream()); String headerValue = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); if (null == headerValue) { throw new BundleException(String.format("Symbolic values not found in '%s'.", manifestUrl), BundleException.MANIFEST_ERROR); diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollection.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollection.java index 2ea67f712f..4a7cb88b19 100644 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollection.java +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollection.java @@ -76,7 +76,7 @@ public void set(String key, String value) { @Override public void add(Class interfaceClass, S service) throws ServiceException { - String className = interfaceClass.getName(); + var className = interfaceClass.getName(); if (null != className2Service.put(interfaceClass.getName(), new FrameworkServiceReference(className, service))) { throw new ServiceException( String.format("Service '%s' is already registered.", interfaceClass.getName()), ServiceException.FACTORY_ERROR); diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/PluginRegistrar.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/PluginRegistrar.java index cdee9893dc..860852f84b 100644 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/PluginRegistrar.java +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/PluginRegistrar.java @@ -39,7 +39,7 @@ public class PluginRegistrar { private static final String PLUGIN_PROPERTIES = "plugin.properties"; public static BundleException register(Bundle bundle) { - PluginRegistrar registrar = new PluginRegistrar(bundle); + var registrar = new PluginRegistrar(bundle); try { registrar.register(); } catch (BundleException e) { diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/SingleSlf4JService.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/SingleSlf4JService.java index 6928621c83..b138237dd6 100644 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/SingleSlf4JService.java +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/SingleSlf4JService.java @@ -459,7 +459,7 @@ public long getTime() { @Override public String toString() { - StringWriter result = new StringWriter(); + var result = new StringWriter(); result.write(message); if (execption.isPresent()) { result.write('\n'); diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/TemporaryLocation.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/TemporaryLocation.java index 2999014d23..ab336c06a9 100644 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/TemporaryLocation.java +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/TemporaryLocation.java @@ -44,7 +44,7 @@ private TemporaryLocation(Location parent, URL defaultValue) { private static URL createTemporaryDirectory() { try { - Path location = Files.createTempDirectory(TEMP_PREFIX); + var location = Files.createTempDirectory(TEMP_PREFIX); return location.toUri().toURL(); } catch (IOException e) { throw new IOError(e); @@ -120,7 +120,7 @@ public Location createLocation(Location parent, URL defaultValue, boolean readon @Override public URL getDataArea(String path) throws IOException { try { - Path locationPath = Paths.get(location.toURI()); + var locationPath = Paths.get(location.toURI()); return locationPath.resolve(path).toUri().toURL(); } catch (URISyntaxException e) { throw new IOException("Location not correctly formatted.", e); @@ -130,7 +130,7 @@ public URL getDataArea(String path) throws IOException { @Override public void close() throws Exception { try { - Path path = Path.of(location.toURI()); + var path = Path.of(location.toURI()); Files.walk(path) .sorted(Comparator.reverseOrder()) .map(Path::toFile) diff --git a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFrameworkTest.java b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFrameworkTest.java index ca76c92ce1..d87f8e417d 100644 --- a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFrameworkTest.java +++ b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFrameworkTest.java @@ -251,7 +251,7 @@ public void println(String x) { @Override public void println(Object x) { if (x instanceof Exception) { - Exception e = (Exception) x; + var e = (Exception) x; if (TEST_EXCEPTION_MESSAGE == e.getMessage()) { messages.add(TEST_EXCEPTION_MESSAGE); } diff --git a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSetTest.java b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSetTest.java index 9c5c97ddb8..ac7bc033cd 100644 --- a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSetTest.java +++ b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSetTest.java @@ -49,7 +49,7 @@ void testAddGet() throws BundleException { @Test void testSameSymbolicName() throws BundleException { - final String symbolicName = "sym.a"; + final var symbolicName = "sym.a"; final long id1 = 12345; final long id2 = 23456; Bundle testBundle1 = new TestBundle(id1, symbolicName); @@ -63,8 +63,8 @@ void testSameSymbolicName() throws BundleException { @Test void testSameID() throws BundleException { - final String symbolicName1 = "sym.a"; - final String symbolicName2 = "sym.b"; + final var symbolicName1 = "sym.a"; + final var symbolicName2 = "sym.b"; final long id = 12345; Bundle testBundle1 = new TestBundle(id, symbolicName1); Bundle testBundle2 = new TestBundle(id, symbolicName2); diff --git a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollectionTest.java b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollectionTest.java index 05f18c475c..5094a9d2d1 100644 --- a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollectionTest.java +++ b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollectionTest.java @@ -39,8 +39,8 @@ void initialize() { @Test void testAddGet() { - Service1 service1 = new Service1(); - Service2 service2 = new Service2(); + var service1 = new Service1(); + var service2 = new Service2(); instance.add(Interf1.class, service1); instance.add(Interf2a.class, service2); instance.add(Interf2b.class, service2); @@ -51,8 +51,8 @@ void testAddGet() { @Test void testMultipleServicesPerInterface() { - Service1 serviceX = new Service1(); - Service1 serviceY = new Service1(); + var serviceX = new Service1(); + var serviceY = new Service1(); instance.add(Interf1.class, serviceX); ServiceException e = assertThrows(ServiceException.class, () -> instance.add(Interf1.class, serviceY)); assertThat(e.getMessage()).as("ServiceException does not contain interface class name.").contains(Interf1.class.getName()); diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImpl.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImpl.java index 4b7f592c3c..e50f9e537e 100644 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImpl.java +++ b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImpl.java @@ -141,7 +141,7 @@ public void activatePlugins(SpotlessEclipsePluginConfig config) { * The HTML formatter only uses the DOCTYPE/SCHEMA for content model selection. * Hence no external URIs are required. */ - boolean allowExternalURI = false; + var allowExternalURI = false; EclipseXmlFormatterStepImpl.FrameworkConfig.activateXmlPlugins(config, allowExternalURI); config.add(new HTMLCorePlugin()); } diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/html/StructuredDocumentProcessor.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/html/StructuredDocumentProcessor.java index 6adc258c78..79a4e5b6a2 100644 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/html/StructuredDocumentProcessor.java +++ b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/html/StructuredDocumentProcessor.java @@ -63,7 +63,7 @@ public StructuredDocumentProcessor(IStructuredDocument document, String type, /** Applies processor on document, using a given formatter */ public void apply(T formatter) { - for (int currentRegionId = 0; currentRegionId < numberOfRegions; currentRegionId++) { + for (var currentRegionId = 0; currentRegionId < numberOfRegions; currentRegionId++) { applyOnRegion(currentRegionId, formatter); } } @@ -132,7 +132,7 @@ public int getLastLine() { } private static int computeIndent(IStructuredDocument document, ITypedRegion region, String htmlIndent) { - int indent = 0; + var indent = 0; try { int lineNumber = document.getLineOfOffset(region.getOffset()); document.getNumberOfLines(); @@ -180,7 +180,7 @@ protected void fixTagIndent(MultiTextEdit modifications, int offset, String inde int lineStart = document.getLineOffset(lineNumber); int lineEnd = document.getLineOffset(lineNumber + 1); String lineContent = document.get(lineStart, lineEnd - lineStart); - StringBuilder currentIndent = new StringBuilder(); + var currentIndent = new StringBuilder(); lineContent.chars().filter(c -> { if (c == ' ' || c == '\t') { currentIndent.append(c); diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/PluginPreferences.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/PluginPreferences.java index 81aa772617..25ea278e4d 100644 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/PluginPreferences.java +++ b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/PluginPreferences.java @@ -96,9 +96,9 @@ public static void configureCatalog(final Properties properties, final ICatalog throw new IllegalArgumentException("Internal error: Catalog implementation '" + defaultCatalogInterface.getClass().getCanonicalName() + "' unsupported."); } Catalog defaultCatalog = (Catalog) defaultCatalogInterface; - String catalogProperty = properties.getProperty(USER_CATALOG, ""); + var catalogProperty = properties.getProperty(USER_CATALOG, ""); if (!catalogProperty.isEmpty()) { - final File catalogFile = new File(catalogProperty); + final var catalogFile = new File(catalogProperty); try { InputStream inputStream = new FileInputStream(catalogFile); String orgBase = defaultCatalog.getBase(); @@ -118,7 +118,7 @@ public static void configureCatalog(final Properties properties, final ICatalog public static void assertNoChanges(Plugin plugin, Properties properties) { Objects.requireNonNull(properties, "Property values are missing."); final String preferenceId = plugin.getBundle().getSymbolicName(); - Properties originalValues = CONFIG.get(preferenceId); + var originalValues = CONFIG.get(preferenceId); if (null == originalValues) { throw new IllegalArgumentException("No configuration found for " + preferenceId); } diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseCssFormatterStepImplTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseCssFormatterStepImplTest.java index 8dda3149c0..7412ade3b6 100644 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseCssFormatterStepImplTest.java +++ b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseCssFormatterStepImplTest.java @@ -41,7 +41,7 @@ void initialize() throws Exception { * All formatter configuration is stored in * org.eclipse.core.runtime/.settings/org.eclipse.wst.css.core.prefs. */ - Properties properties = new Properties(); + var properties = new Properties(); properties.put(INDENTATION_SIZE, "3"); properties.put(INDENTATION_CHAR, SPACE); //Default is TAB properties.put(CLEANUP_CASE_SELECTOR, Integer.toString(UPPER)); //Done by cleanup diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImplTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImplTest.java index b75421692a..e71080fcf9 100644 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImplTest.java +++ b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImplTest.java @@ -40,7 +40,7 @@ void initialize() throws Exception { * org.eclipse.core.runtime/.settings/org.eclipse.wst.xml.core.prefs. * So a simple test of one configuration item change is considered sufficient. */ - Properties properties = new Properties(); + var properties = new Properties(); properties.put(CLEANUP_TAG_NAME_CASE, Integer.toString(HTMLCorePreferenceNames.UPPER)); //HTML config properties.put(FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON, JavaScriptCore.INSERT); //JS config properties.put(QUOTE_ATTR_VALUES, "TRUE"); //CSS config @@ -89,7 +89,7 @@ void formatCSS() throws Exception { @Test void checkCleanupForNonUtf8() throws Exception { - String osEncoding = System.getProperty("file.encoding"); + var osEncoding = System.getProperty("file.encoding"); System.setProperty("file.encoding", "ISO-8859-1"); //Simulate a non UTF-8 OS String[] input = testData.input("utf-8.html"); String output = formatter.format(input[0]); diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsFormatterStepImplTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsFormatterStepImplTest.java index 0858c3a04d..96dacc167f 100644 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsFormatterStepImplTest.java +++ b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsFormatterStepImplTest.java @@ -50,7 +50,7 @@ void initialize() throws Exception { * All formatter configuration is stored in * org.eclipse.core.runtime/.settings/org.eclipse.jst.jsdt.core.prefs. */ - Properties properties = new Properties(); + var properties = new Properties(); properties.setProperty(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaScriptCore.TAB); formatter = new EclipseJsFormatterStepImpl(properties); } diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsonFormatterStepImplTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsonFormatterStepImplTest.java index 3bb3b7c988..18af11725b 100644 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsonFormatterStepImplTest.java +++ b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsonFormatterStepImplTest.java @@ -41,7 +41,7 @@ void initialize() throws Exception { * org.eclipse.core.runtime/.settings/org.eclipse.wst.json.core.prefs. * So a simple test of one configuration item change is considered sufficient. */ - Properties properties = new Properties(); + var properties = new Properties(); properties.put(INDENTATION_SIZE, "3"); //Default is 1 properties.put(INDENTATION_CHAR, SPACE); //Default is TAB properties.put(CASE_PROPERTY_NAME, Integer.toString(UPPER)); //Dead code, ignored diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplAllowExternalURIsTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplAllowExternalURIsTest.java index ac3b2c45f6..1e4a19ca2b 100644 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplAllowExternalURIsTest.java +++ b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplAllowExternalURIsTest.java @@ -41,7 +41,7 @@ void initializeStatic() throws Exception { * org.eclipse.core.runtime/.settings/org.eclipse.wst.xml.core.prefs. * So a simple test of one configuration item change is considered sufficient. */ - Properties properties = new Properties(); + var properties = new Properties(); properties.put(PluginPreferences.RESOLVE_EXTERNAL_URI, "TRUE"); properties.put(INDENTATION_SIZE, "2"); properties.put(INDENTATION_CHAR, SPACE); //Default is TAB diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplCatalogLookupTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplCatalogLookupTest.java index a9ccd85720..cee2f48d57 100644 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplCatalogLookupTest.java +++ b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplCatalogLookupTest.java @@ -41,7 +41,7 @@ void initializeStatic() throws Exception { * org.eclipse.core.runtime/.settings/org.eclipse.wst.xml.core.prefs. * So a simple test of one configuration item change is considered sufficient. */ - Properties properties = new Properties(); + var properties = new Properties(); properties.put(INDENTATION_SIZE, "2"); properties.put(INDENTATION_CHAR, SPACE); //Default is TAB properties.put(PluginPreferences.USER_CATALOG, testData.getRestrictionsPath("catalog.xml").toString()); diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplTest.java index 88b15c42e2..cd4a1068b7 100644 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplTest.java +++ b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplTest.java @@ -42,7 +42,7 @@ void initialize() throws Exception { * org.eclipse.core.runtime/.settings/org.eclipse.wst.xml.core.prefs. * So a simple test of one configuration item change is considered sufficient. */ - Properties properties = new Properties(); + var properties = new Properties(); properties.put(INDENTATION_SIZE, "2"); properties.put(INDENTATION_CHAR, SPACE); //Default is TAB formatter = new EclipseXmlFormatterStepImpl(properties); diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/TestData.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/TestData.java index d767337970..c37e4bc4a4 100644 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/TestData.java +++ b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/TestData.java @@ -22,8 +22,8 @@ public class TestData { public static TestData getTestDataOnFileSystem(String kind) { - final String userDir = System.getProperty("user.dir", "."); - Path dataPath = Paths.get(userDir, "src", "test", "resources", kind); + final var userDir = System.getProperty("user.dir", "."); + var dataPath = Paths.get(userDir, "src", "test", "resources", kind); if (Files.isDirectory(dataPath)) { return new TestData(dataPath); } @@ -46,12 +46,12 @@ private TestData(Path dataPath) { } public String[] input(final String fileName) throws Exception { - Path xmlPath = inputPath.resolve(fileName); + var xmlPath = inputPath.resolve(fileName); return new String[]{read(xmlPath), xmlPath.toString()}; } public String expected(final String fileName) { - Path xmlPath = expectedPath.resolve(fileName); + var xmlPath = expectedPath.resolve(fileName); return read(xmlPath); } @@ -60,7 +60,7 @@ private String read(final Path xmlPath) { throw new IllegalArgumentException(String.format("'%1$s' is not a regular file.", xmlPath)); } try { - String checkedOutFileContent = new String(java.nio.file.Files.readAllBytes(xmlPath), "UTF8"); + var checkedOutFileContent = new String(java.nio.file.Files.readAllBytes(xmlPath), "UTF8"); return checkedOutFileContent.replace("\r", ""); //Align GIT end-of-line normalization } catch (IOException e) { throw new IllegalArgumentException(String.format("Failed to read '%1$s'.", xmlPath), e); @@ -68,7 +68,7 @@ private String read(final Path xmlPath) { } public Path getRestrictionsPath(String fileName) { - Path filePath = restrictionsPath.resolve(fileName); + var filePath = restrictionsPath.resolve(fileName); if (!Files.exists(filePath)) { throw new IllegalArgumentException(String.format("'%1$s' is not a restrictions file.", fileName)); } diff --git a/lib-extra/src/groovy/java/com/diffplug/spotless/extra/glue/groovy/GrEclipseFormatterStepImpl.java b/lib-extra/src/groovy/java/com/diffplug/spotless/extra/glue/groovy/GrEclipseFormatterStepImpl.java index 9549847d74..5bf5f90f60 100644 --- a/lib-extra/src/groovy/java/com/diffplug/spotless/extra/glue/groovy/GrEclipseFormatterStepImpl.java +++ b/lib-extra/src/groovy/java/com/diffplug/spotless/extra/glue/groovy/GrEclipseFormatterStepImpl.java @@ -89,7 +89,7 @@ public GrEclipseFormatterStepImpl(final Properties properties) throws Exception /** Formatting Groovy string */ public String format(String raw) throws Exception { IDocument doc = new Document(raw); - GroovyErrorListener errorListener = new GroovyErrorListener(); + var errorListener = new GroovyErrorListener(); TextSelection selectAll = new TextSelection(doc, 0, doc.getLength()); GroovyFormatter codeFormatter = new DefaultGroovyFormatter(selectAll, doc, preferencesStore, false); TextEdit edit = codeFormatter.format(); @@ -135,7 +135,7 @@ public boolean errorsDetected() { @Override public String toString() { - StringBuilder string = new StringBuilder(); + var string = new StringBuilder(); if (1 < errors.size()) { string.append("Multiple problems detected during step execution:"); } else if (0 == errors.size()) { @@ -168,9 +168,9 @@ public void log(TraceCategory arg0, String arg1) { private static PreferenceStore createPreferences(final Properties properties) throws IOException { final PreferenceStore preferences = new PreferenceStore(); - ByteArrayOutputStream output = new ByteArrayOutputStream(); + var output = new ByteArrayOutputStream(); properties.store(output, null); - ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray()); + var input = new ByteArrayInputStream(output.toByteArray()); preferences.load(input); return preferences; } 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..2e4a5c2a78 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. @@ -84,14 +84,14 @@ public FormatterStep build() { /** Set dependencies for the corresponding Eclipse version */ public void setVersion(String version) { - String url = "/" + ECLIPSE_FORMATTER_RESOURCES + "/" + formatterName.replace(' ', '_') + "/v" + version + ".lockfile"; - InputStream depsFile = EclipseBasedStepBuilder.class.getResourceAsStream(url); + var url = "/" + ECLIPSE_FORMATTER_RESOURCES + "/" + formatterName.replace(' ', '_') + "/v" + version + ".lockfile"; + var depsFile = EclipseBasedStepBuilder.class.getResourceAsStream(url); if (depsFile == null) { throw new IllegalArgumentException("No such version " + version + ", expected at " + url); } - byte[] content = toByteArray(depsFile); - String allLines = new String(content, StandardCharsets.UTF_8); - String[] lines = allLines.split("\n"); + var content = toByteArray(depsFile); + var allLines = new String(content, StandardCharsets.UTF_8); + var lines = allLines.split("\n"); dependencies.clear(); for (String line : lines) { if (!line.startsWith("#")) { @@ -102,11 +102,11 @@ public void setVersion(String version) { } private static byte[] toByteArray(InputStream in) { - ByteArrayOutputStream to = new ByteArrayOutputStream(); - byte[] buf = new byte[8192]; + var to = new ByteArrayOutputStream(); + var buf = new byte[8192]; try { while (true) { - int r = in.read(buf); + var r = in.read(buf); if (r == -1) { break; } @@ -164,10 +164,10 @@ protected State(String formatterVersion, String formatterStepExt, Provisioner ja } private static String convertEclipseVersion(String version) { - String semanticVersion = version; + var semanticVersion = version; //Old Eclipse versions used a character at the end. For example '4.7.3a'. if (1 < version.length()) { - char lastChar = version.charAt(version.length() - 1); + var lastChar = version.charAt(version.length() - 1); if ('.' != lastChar && 'a' <= lastChar) { semanticVersion = version.substring(0, version.length() - 1); semanticVersion += String.format(".%d", (int) lastChar); diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/EquoBasedStepBuilder.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/EquoBasedStepBuilder.java index cc12a938ad..d52c3262c7 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/EquoBasedStepBuilder.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/EquoBasedStepBuilder.java @@ -76,7 +76,7 @@ protected void addPlatformRepo(P2Model model, String version) { if (!version.startsWith("4.")) { throw new IllegalArgumentException("Expected 4.x"); } - int minorVersion = Integer.parseInt(version.substring("4.".length())); + var minorVersion = Integer.parseInt(version.substring("4.".length())); model.addP2Repo("https://download.eclipse.org/eclipse/updates/" + version + "/"); model.getInstall().addAll(List.of( @@ -115,7 +115,7 @@ private P2Model createModelWithMirrors() { ArrayList p2Repos = new ArrayList<>(model.getP2repo()); p2Repos.replaceAll(url -> { for (Map.Entry mirror : p2Mirrors.entrySet()) { - String prefix = mirror.getKey(); + var prefix = mirror.getKey(); if (url.startsWith(prefix)) { return mirror.getValue() + url.substring(prefix.length()); } diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java index fb54be4ba0..725c77efc3 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java @@ -90,10 +90,10 @@ static class RelocatablePolicy extends LazyForwardingEquality imp @Override protected CachedEndings calculateState() throws Exception { - Runtime runtime = new RuntimeInit(projectDir).atRuntime(); + var runtime = new RuntimeInit(projectDir).atRuntime(); // LazyForwardingEquality guarantees that this will only be called once, and keeping toFormat // causes a memory leak, see https://github.com/diffplug/spotless/issues/1194 - CachedEndings state = new CachedEndings(projectDir, runtime, toFormat.get()); + var state = new CachedEndings(projectDir, runtime, toFormat.get()); projectDir = null; toFormat = null; return state; @@ -121,7 +121,7 @@ static class CachedEndings implements Serializable { rootDir = rootPath.equals("/") ? rootPath : rootPath + "/"; defaultEnding = runtime.defaultEnding; for (File file : toFormat) { - String ending = runtime.getEndingFor(file); + var ending = runtime.getEndingFor(file); if (!ending.equals(defaultEnding)) { String absPath = FileSignature.pathNativeToUnix(file.getAbsolutePath()); String subPath = FileSignature.subpath(rootDir, absPath); @@ -231,10 +231,10 @@ private Runtime(List infoRules, @Nullable File workTree, Config public String getEndingFor(File file) { // handle the info rules first, since they trump everything if (workTree != null && !infoRules.isEmpty()) { - String rootPath = workTree.getAbsolutePath(); - String path = file.getAbsolutePath(); + var rootPath = workTree.getAbsolutePath(); + var path = file.getAbsolutePath(); if (path.startsWith(rootPath)) { - String subpath = path.substring(rootPath.length() + 1); + var subpath = path.substring(rootPath.length() + 1); String infoResult = findAttributeInRules(subpath, IS_FOLDER, KEY_EOL, infoRules); if (infoResult != null) { return convertEolToLineEnding(infoResult, file); @@ -243,7 +243,7 @@ public String getEndingFor(File file) { } // handle the local .gitattributes (if any) - String localResult = cache.valueFor(file, KEY_EOL); + var localResult = cache.valueFor(file, KEY_EOL); if (localResult != null) { return convertEolToLineEnding(localResult, file); } @@ -311,13 +311,13 @@ static class AttributesCache { /** Returns a value if there is one, or unspecified if there isn't. */ public @Nullable String valueFor(File file, String key) { - StringBuilder pathBuilder = new StringBuilder(file.getAbsolutePath().length()); - boolean isDirectory = file.isDirectory(); - File parent = file.getParentFile(); + var pathBuilder = new StringBuilder(file.getAbsolutePath().length()); + var isDirectory = file.isDirectory(); + var parent = file.getParentFile(); pathBuilder.append(file.getName()); while (parent != null) { - String path = pathBuilder.toString(); + var path = pathBuilder.toString(); String value = findAttributeInRules(path, isDirectory, key, getRulesForFolder(parent)); if (value != null) { 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..ec4655fd75 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 @@ -96,16 +96,16 @@ public boolean isClean(Project project, ObjectId treeSha, String relativePathUni DirCacheIterator dirCacheIterator = treeWalk.getTree(INDEX, DirCacheIterator.class); WorkingTreeIterator workingTreeIterator = treeWalk.getTree(WORKDIR, WorkingTreeIterator.class); - boolean hasTree = treeIterator != null; - boolean hasDirCache = dirCacheIterator != null; + var hasTree = treeIterator != null; + var hasDirCache = dirCacheIterator != null; if (!hasTree) { // it's not in the tree, so it was added return false; } else { if (hasDirCache) { - boolean treeEqualsIndex = treeIterator.idEqual(dirCacheIterator) && treeIterator.getEntryRawMode() == dirCacheIterator.getEntryRawMode(); - boolean indexEqualsWC = !workingTreeIterator.isModified(dirCacheIterator.getDirCacheEntry(), true, treeWalk.getObjectReader()); + var treeEqualsIndex = treeIterator.idEqual(dirCacheIterator) && treeIterator.getEntryRawMode() == dirCacheIterator.getEntryRawMode(); + var indexEqualsWC = !workingTreeIterator.isModified(dirCacheIterator.getDirCacheEntry(), true, treeWalk.getObjectReader()); if (treeEqualsIndex != indexEqualsWC) { // if one is equal and the other isn't, then it has definitely changed return false; @@ -206,7 +206,7 @@ public synchronized ObjectId subtreeShaOf(Project project, ObjectId rootTreeSha) ObjectId subtreeSha = subtreeShaCache.get(project); if (subtreeSha == null) { Repository repo = repositoryFor(project); - File directory = getDir(project); + var directory = getDir(project); if (repo.getWorkTree().equals(directory)) { subtreeSha = rootTreeSha; } else { 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..f970e0ca96 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. @@ -75,7 +75,7 @@ static RepositorySpecificResolver fileRepositoryResolverForProject(File projectD * @return the builder. */ static RepositorySpecificResolver fileRepositoryResolverForProject(File projectDir, @Nullable Config baseConfig) { - RepositorySpecificResolver repositoryResolver = new RepositorySpecificResolver(baseConfig); + var repositoryResolver = new RepositorySpecificResolver(baseConfig); repositoryResolver.findGitDir(projectDir); repositoryResolver.readEnvironment(); if (repositoryResolver.getGitDir() != null || repositoryResolver.getWorkTree() != null) { @@ -183,7 +183,7 @@ protected void setupGitDir() throws IOException { } String commonPath = RawParseUtils.decode(content, 0, lineEnd); - File common = new File(commonPath); + var common = new File(commonPath); if (common.isAbsolute()) { commonDirectory = common; } else { diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/cpp/EclipseCdtFormatterStep.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/cpp/EclipseCdtFormatterStep.java index 1a83389eaa..ad7d240ff8 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/cpp/EclipseCdtFormatterStep.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/cpp/EclipseCdtFormatterStep.java @@ -67,8 +67,8 @@ private static FormatterFunc apply(EquoBasedStepBuilder.State state) throws Exce try { return (String) method.invoke(formatter, input); } catch (InvocationTargetException exceptionWrapper) { - Throwable throwable = exceptionWrapper.getTargetException(); - Exception exception = (throwable instanceof Exception) ? (Exception) throwable : null; + var throwable = exceptionWrapper.getTargetException(); + var exception = (throwable instanceof Exception) ? (Exception) throwable : null; throw (null == exception) ? exceptionWrapper : exception; } }); diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStep.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStep.java index 08c28889f9..ea8846f4dc 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStep.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStep.java @@ -91,8 +91,8 @@ private static FormatterFunc apply(EquoBasedStepBuilder.State state) throws Exce try { return (String) method.invoke(formatter, input); } catch (InvocationTargetException exceptionWrapper) { - Throwable throwable = exceptionWrapper.getTargetException(); - Exception exception = (throwable instanceof Exception) ? (Exception) throwable : null; + var throwable = exceptionWrapper.getTargetException(); + var exception = (throwable instanceof Exception) ? (Exception) throwable : null; throw (null == exception) ? exceptionWrapper : exception; } }); diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/integration/DiffMessageFormatter.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/integration/DiffMessageFormatter.java index 55336e8c04..65af376245 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 @@ -102,7 +102,7 @@ public Charset getEncoding() { @Override public String getFormatted(File file, String rawUnix) { - Path clean = cleanDir.resolve(rootDir.relativize(file.toPath())); + var clean = cleanDir.resolve(rootDir.relativize(file.toPath())); byte[] content = Errors.rethrow().get(() -> Files.readAllBytes(clean)); return new String(content, encoding); } @@ -143,7 +143,7 @@ public String getMessage() { Objects.requireNonNull(runToFix, "runToFix"); Objects.requireNonNull(formatter, "formatter"); Objects.requireNonNull(problemFiles, "problemFiles"); - DiffMessageFormatter diffFormater = new DiffMessageFormatter(formatter, problemFiles); + var diffFormater = new DiffMessageFormatter(formatter, problemFiles); return "The following files had format violations:\n" + diffFormater.buffer + runToFix; @@ -165,11 +165,11 @@ private DiffMessageFormatter(CleanProvider formatter, List problemFiles) t this.formatter = Objects.requireNonNull(formatter, "formatter"); ListIterator problemIter = problemFiles.listIterator(); while (problemIter.hasNext() && numLines < MAX_CHECK_MESSAGE_LINES) { - File file = problemIter.next(); + var file = problemIter.next(); addFile(relativePath(file) + "\n" + diff(file)); } if (problemIter.hasNext()) { - int remainingFiles = problemFiles.size() - problemIter.nextIndex(); + var remainingFiles = problemFiles.size() - problemIter.nextIndex(); if (remainingFiles >= MAX_FILES_TO_LIST) { buffer.append("Violations also present in ").append(remainingFiles).append(" other files.\n"); } else { @@ -199,7 +199,7 @@ private void addFile(String arg) { if (!lines.isEmpty()) { addIntendedLine(NORMAL_INDENT, lines.get(0)); } - for (int i = 1; i < Math.min(MIN_LINES_PER_FILE, lines.size()); ++i) { + for (var i = 1; i < Math.min(MIN_LINES_PER_FILE, lines.size()); ++i) { addIntendedLine(DIFF_INDENT, lines.get(i)); } @@ -212,7 +212,7 @@ private void addFile(String arg) { if (numLines >= MAX_CHECK_MESSAGE_LINES) { // we're out of space if (iter.hasNext()) { - int linesLeft = lines.size() - iter.nextIndex(); + var linesLeft = lines.size() - iter.nextIndex(); addIntendedLine(NORMAL_INDENT, "... (" + linesLeft + " more lines that didn't fit)"); } } @@ -234,9 +234,9 @@ private void addIntendedLine(String indent, String line) { * sequence (\n, \r, \r\n). */ private String diff(File file) throws IOException { - String raw = new String(Files.readAllBytes(file.toPath()), formatter.getEncoding()); + var raw = new String(Files.readAllBytes(file.toPath()), formatter.getEncoding()); String rawUnix = LineEnding.toUnix(raw); - String formatted = formatter.getFormatted(file, rawUnix); + var formatted = formatter.getFormatted(file, rawUnix); String formattedUnix = LineEnding.toUnix(formatted); if (rawUnix.equals(formattedUnix)) { @@ -263,11 +263,11 @@ private static String diffWhitespaceLineEndings(String dirty, String clean, bool EditList edits = new EditList(); edits.addAll(MyersDiff.INSTANCE.diff(RawTextComparator.DEFAULT, a, b)); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + var out = new ByteArrayOutputStream(); try (DiffFormatter formatter = new DiffFormatter(out)) { formatter.format(edits, a, b); } - String formatted = out.toString(StandardCharsets.UTF_8.name()); + var formatted = out.toString(StandardCharsets.UTF_8.name()); // 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..aee02383d2 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. @@ -17,7 +17,6 @@ import java.io.File; import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import java.util.Properties; import com.diffplug.spotless.FormatterFunc; @@ -61,13 +60,13 @@ private static FormatterFunc applyWithoutFile(String className, EclipseBasedStep JVM_SUPPORT.assertFormatterSupported(state.getSemanticVersion()); Class formatterClazz = state.loadClass(FORMATTER_PACKAGE + className); Object formatter = formatterClazz.getConstructor(Properties.class).newInstance(state.getPreferences()); - Method method = formatterClazz.getMethod(FORMATTER_METHOD, String.class); + var method = formatterClazz.getMethod(FORMATTER_METHOD, String.class); return input -> { try { return (String) method.invoke(formatter, input); } catch (InvocationTargetException exceptionWrapper) { - Throwable throwable = exceptionWrapper.getTargetException(); - Exception exception = (throwable instanceof Exception) ? (Exception) throwable : null; + var throwable = exceptionWrapper.getTargetException(); + var exception = (throwable instanceof Exception) ? (Exception) throwable : null; throw (null == exception) ? exceptionWrapper : exception; } }; @@ -77,7 +76,7 @@ private static FormatterFunc applyWithFile(String className, EclipseBasedStepBui JVM_SUPPORT.assertFormatterSupported(state.getSemanticVersion()); 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); + var 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 { 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..fa84cc7ff7 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 @@ -34,7 +34,7 @@ class GitAttributesTest extends ResourceHarness { private List testFiles(String prefix) { List result = new ArrayList<>(); for (String path : TEST_PATHS) { - String prefixedPath = prefix + path; + var prefixedPath = prefix + path; setFile(prefixedPath).toContent(""); result.add(newFile(prefixedPath)); } diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/GitRachetMergeBaseTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/GitRachetMergeBaseTest.java index 02447a36bd..4f7dd343aa 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/GitRachetMergeBaseTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/GitRachetMergeBaseTest.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. @@ -108,8 +108,8 @@ public void onlyDirty(String... filenames) throws IOException { if (!file.isFile()) { continue; } - boolean expectedClean = !dirtyFiles.contains(file.getName()); - for (int i = 0; i < shas.length; ++i) { + var expectedClean = !dirtyFiles.contains(file.getName()); + for (var i = 0; i < shas.length; ++i) { assertClean(i, file.getName(), expectedClean); } } diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/eclipse/EclipseResourceHarness.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/eclipse/EclipseResourceHarness.java index 71cb4b78de..814210f40a 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/eclipse/EclipseResourceHarness.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/eclipse/EclipseResourceHarness.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. @@ -78,7 +78,7 @@ public EclipseResourceHarness(EclipseBasedStepBuilder builder, String sourceFile * @return Formatted string */ protected String assertFormatted(String formatterVersion, File... settingsFiles) throws Exception { - String output = format(formatterVersion, settingsFiles); + var output = format(formatterVersion, settingsFiles); assertThat(output).isEqualTo(expected); return output; } diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/eclipse/EquoResourceHarness.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/eclipse/EquoResourceHarness.java index 8d5d955c02..31d8f39dfd 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/eclipse/EquoResourceHarness.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/eclipse/EquoResourceHarness.java @@ -78,7 +78,7 @@ public EquoResourceHarness(EquoBasedStepBuilder builder, String sourceFileName, * @return Formatted string */ protected String assertFormatted(String formatterVersion, File... settingsFiles) throws Exception { - String output = format(formatterVersion, settingsFiles); + var output = format(formatterVersion, settingsFiles); assertThat(output).isEqualTo(expected); return output; } diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStepTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStepTest.java index 9517c24121..565e578f47 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStepTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStepTest.java @@ -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. @@ -59,11 +59,11 @@ private static Stream formatWithVersion() { */ @Test void multipleConfigurations() throws Exception { - File tabPropertyFile = createPropertyFile(config -> { + var tabPropertyFile = createPropertyFile(config -> { config.setProperty("indentationChar", "tab"); config.setProperty("indentationSize", "1"); }); - File spacePropertyFile = createPropertyFile(config -> { + var spacePropertyFile = createPropertyFile(config -> { config.setProperty("indentationChar", "space"); config.setProperty("indentationSize", "5"); }); @@ -72,9 +72,9 @@ void multipleConfigurations() throws Exception { } private File createPropertyFile(Consumer config) throws IOException { - Properties configProps = new Properties(); + var configProps = new Properties(); config.accept(configProps); - File tempFile = File.createTempFile("EclipseWtpFormatterStepTest-", ".properties"); + var tempFile = File.createTempFile("EclipseWtpFormatterStepTest-", ".properties"); OutputStream tempOut = new FileOutputStream(tempFile); configProps.store(tempOut, "test properties"); tempOut.flush(); 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..2fed1aeadf 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 @@ -58,7 +58,7 @@ public JavaCleanthatRefactorerFunc() { @Override public String apply(String input) throws Exception { // https://stackoverflow.com/questions/1771679/difference-between-threads-context-class-loader-and-normal-classloader - ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + var originalClassLoader = Thread.currentThread().getContextClassLoader(); try { // Ensure CleanThat main Thread has its custom classLoader while executing its refactoring Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); diff --git a/lib/src/compatKtLint0Dot46Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot46Dot0Adapter.java b/lib/src/compatKtLint0Dot46Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot46Dot0Adapter.java index afaf2ad19f..e51d7b6881 100644 --- a/lib/src/compatKtLint0Dot46Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot46Dot0Adapter.java +++ b/lib/src/compatKtLint0Dot46Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot46Dot0Adapter.java @@ -54,7 +54,7 @@ public String format(final String text, Path path, final boolean isScript, final boolean useExperimental, Path editorConfigPath, final Map userData, final Map editorConfigOverrideMap) { - final FormatterCallback formatterCallback = new FormatterCallback(); + final var formatterCallback = new FormatterCallback(); final List rulesets = new ArrayList<>(); rulesets.add(new StandardRuleSetProvider().get()); diff --git a/lib/src/compatKtLint0Dot47Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot47Dot0Adapter.java b/lib/src/compatKtLint0Dot47Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot47Dot0Adapter.java index 0a38730b6a..c688f636ac 100644 --- a/lib/src/compatKtLint0Dot47Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot47Dot0Adapter.java +++ b/lib/src/compatKtLint0Dot47Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot47Dot0Adapter.java @@ -60,7 +60,7 @@ public String format(final String text, Path path, final boolean isScript, final boolean useExperimental, Path editorConfigPath, final Map userData, final Map editorConfigOverrideMap) { - final FormatterCallback formatterCallback = new FormatterCallback(); + final var formatterCallback = new FormatterCallback(); Set allRuleProviders = new LinkedHashSet<>( new StandardRuleSetProvider().getRuleProviders()); diff --git a/lib/src/compatKtLint0Dot48Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot48Dot0Adapter.java b/lib/src/compatKtLint0Dot48Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot48Dot0Adapter.java index 1e54a80859..ecf27ede9f 100644 --- a/lib/src/compatKtLint0Dot48Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot48Dot0Adapter.java +++ b/lib/src/compatKtLint0Dot48Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot48Dot0Adapter.java @@ -82,7 +82,7 @@ public String format(final String text, Path path, final boolean isScript, final boolean useExperimental, Path editorConfigPath, final Map userData, final Map editorConfigOverrideMap) { - final FormatterCallback formatterCallback = new FormatterCallback(); + final var formatterCallback = new FormatterCallback(); Set allRuleProviders = new LinkedHashSet<>( new StandardRuleSetProvider().getRuleProviders()); @@ -111,7 +111,7 @@ public String format(final String text, Path path, final boolean isScript, editorConfig, editorConfigOverride, false) - .format(path, formatterCallback); + .format(path, formatterCallback); } /** @@ -137,14 +137,14 @@ private static EditorConfigOverride createEditorConfigOverride(final List if (property != null) { return new Pair<>(property, entry.getValue()); } else if (entry.getKey().startsWith("ktlint_")) { - String[] parts = entry.getKey().substring(7).split("_", 2); + var parts = entry.getKey().substring(7).split("_", 2); if (parts.length == 1) { // convert ktlint_{ruleset} to {ruleset} - String qualifiedRuleId = parts[0] + ":"; + var qualifiedRuleId = parts[0] + ":"; property = RuleExecutionEditorConfigPropertyKt.createRuleSetExecutionEditorConfigProperty(qualifiedRuleId); } else { // convert ktlint_{ruleset}_{rulename} to {ruleset}:{rulename} - String qualifiedRuleId = parts[0] + ":" + parts[1]; + var qualifiedRuleId = parts[0] + ":" + parts[1]; property = RuleExecutionEditorConfigPropertyKt.createRuleExecutionEditorConfigProperty(qualifiedRuleId); } return new Pair<>(property, entry.getValue()); diff --git a/lib/src/diktat/java/com/diffplug/spotless/glue/diktat/DiktatFormatterFunc.java b/lib/src/diktat/java/com/diffplug/spotless/glue/diktat/DiktatFormatterFunc.java index 0b9d115c2b..346804febd 100644 --- a/lib/src/diktat/java/com/diffplug/spotless/glue/diktat/DiktatFormatterFunc.java +++ b/lib/src/diktat/java/com/diffplug/spotless/glue/diktat/DiktatFormatterFunc.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. @@ -78,7 +78,7 @@ public String applyWithFile(String unix, File file) throws Exception { false)); if (!errors.isEmpty()) { - StringBuilder error = new StringBuilder(); + var error = new StringBuilder(); error.append("There are ").append(errors.size()).append(" unfixed errors:"); for (LintError er : errors) { error.append(System.lineSeparator()) diff --git a/lib/src/gson/java/com/diffplug/spotless/glue/gson/GsonFormatterFunc.java b/lib/src/gson/java/com/diffplug/spotless/glue/gson/GsonFormatterFunc.java index 0ff5037cba..fba74d9a21 100644 --- a/lib/src/gson/java/com/diffplug/spotless/glue/gson/GsonFormatterFunc.java +++ b/lib/src/gson/java/com/diffplug/spotless/glue/gson/GsonFormatterFunc.java @@ -61,7 +61,7 @@ public String apply(String inputString) { if (gsonConfig.isSortByKeys()) { jsonElement = sortByKeys(jsonElement); } - try (StringWriter stringWriter = new StringWriter()) { + try (var stringWriter = new StringWriter()) { JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.setIndent(this.generatedIndent); gson.toJson(jsonElement, jsonWriter); diff --git a/lib/src/jackson/java/com/diffplug/spotless/glue/yaml/JacksonYamlFormatterFunc.java b/lib/src/jackson/java/com/diffplug/spotless/glue/yaml/JacksonYamlFormatterFunc.java index b4f8ca6aee..9ee996068d 100644 --- a/lib/src/jackson/java/com/diffplug/spotless/glue/yaml/JacksonYamlFormatterFunc.java +++ b/lib/src/jackson/java/com/diffplug/spotless/glue/yaml/JacksonYamlFormatterFunc.java @@ -73,7 +73,7 @@ protected String format(ObjectMapper objectMapper, String input) throws IllegalA // https://github.com/FasterXML/jackson-dataformats-text/issues/66#issuecomment-554265055 // https://github.com/FasterXML/jackson-dataformats-text/issues/66#issuecomment-554265055 - StringWriter stringWriter = new StringWriter(); + var stringWriter = new StringWriter(); objectMapper.writer().writeValues(stringWriter).writeAll(documents).close(); return stringWriter.toString(); } catch (JsonProcessingException e) { diff --git a/lib/src/ktlint/java/com/diffplug/spotless/glue/ktlint/KtlintFormatterFunc.java b/lib/src/ktlint/java/com/diffplug/spotless/glue/ktlint/KtlintFormatterFunc.java index 02ff5355e3..bd10bf37db 100644 --- a/lib/src/ktlint/java/com/diffplug/spotless/glue/ktlint/KtlintFormatterFunc.java +++ b/lib/src/ktlint/java/com/diffplug/spotless/glue/ktlint/KtlintFormatterFunc.java @@ -37,7 +37,7 @@ public class KtlintFormatterFunc implements FormatterFunc.NeedsFile { public KtlintFormatterFunc(String version, boolean isScript, boolean useExperimental, FileSignature editorConfigPath, Map userData, Map editorConfigOverrideMap) { - int minorVersion = Integer.parseInt(version.split("\\.")[1]); + var minorVersion = Integer.parseInt(version.split("\\.")[1]); if (minorVersion >= 48) { // ExperimentalParams lost two constructor arguments, EditorConfigProperty moved to its own class this.adapter = new KtLintCompat0Dot48Dot0Adapter(); diff --git a/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java b/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java index 3e4bb3423b..f2a2ac895d 100644 --- a/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java +++ b/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java @@ -18,8 +18,6 @@ import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; @@ -34,16 +32,16 @@ class EncodingErrorMsg { private static int CONTEXT = 3; static @Nullable String msg(String chars, byte[] bytes, Charset charset) { - int unrepresentable = chars.indexOf(UNREPRESENTABLE); + var unrepresentable = chars.indexOf(UNREPRESENTABLE); if (unrepresentable == -1) { return null; } // sometimes the '�' is really in a file, such as for *this* file // so we have to handle that corner case - ByteBuffer byteBuf = ByteBuffer.wrap(bytes); - CharBuffer charBuf = CharBuffer.allocate(chars.length()); - CoderResult result = charset.newDecoder() + var byteBuf = ByteBuffer.wrap(bytes); + var charBuf = CharBuffer.allocate(chars.length()); + var result = charset.newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) .decode(byteBuf, charBuf, true); @@ -73,10 +71,10 @@ private EncodingErrorMsg(String chars, ByteBuffer byteBuf, Charset charset, int message.append("You configured Spotless to use " + charset.name() + "."); } - int line = 1; - int col = 1; - for (int i = 0; i < unrepresentable; ++i) { - char c = chars.charAt(i); + var line = 1; + var col = 1; + for (var i = 0; i < unrepresentable; ++i) { + var c = chars.charAt(i); if (c == '\n') { ++line; col = 1; @@ -118,10 +116,10 @@ private void appendExample(Charset charset, boolean must) { byteBuf.clear(); charBuf.clear(); - CharsetDecoder decoder = charset.newDecoder(); + var decoder = charset.newDecoder(); if (!must) { // bail early if we can - CoderResult r = decoder + var r = decoder .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) .decode(byteBuf, charBuf, true); @@ -136,8 +134,8 @@ private void appendExample(Charset charset, boolean must) { } charBuf.flip(); - int start = Math.max(unrepresentable - CONTEXT, 0); - int end = Math.min(charBuf.limit(), unrepresentable + CONTEXT + 1); + var start = Math.max(unrepresentable - CONTEXT, 0); + var end = Math.min(charBuf.limit(), unrepresentable + CONTEXT + 1); message.append('\n'); message.append(charBuf.subSequence(start, end).toString() .replace('\n', '␤') diff --git a/lib/src/main/java/com/diffplug/spotless/FeatureClassLoader.java b/lib/src/main/java/com/diffplug/spotless/FeatureClassLoader.java index d07e7e4324..712e53ec5e 100644 --- a/lib/src/main/java/com/diffplug/spotless/FeatureClassLoader.java +++ b/lib/src/main/java/com/diffplug/spotless/FeatureClassLoader.java @@ -17,7 +17,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.nio.ByteBuffer; @@ -63,8 +62,8 @@ class FeatureClassLoader extends URLClassLoader { @Override protected Class findClass(String name) throws ClassNotFoundException { if (name.startsWith("com.diffplug.spotless.glue.") || name.startsWith("com.diffplug.spotless.extra.glue.")) { - String path = name.replace('.', '/') + ".class"; - URL url = findResource(path); + var path = name.replace('.', '/') + ".class"; + var url = findResource(path); if (url == null) { throw new ClassNotFoundException(name); } @@ -92,7 +91,7 @@ private static boolean useBuildToolClassLoader(String name) { @Override public URL findResource(String name) { - URL resource = super.findResource(name); + var resource = super.findResource(name); if (resource != null) { return resource; } @@ -100,8 +99,8 @@ public URL findResource(String name) { } private static ByteBuffer urlToByteBuffer(URL url) throws IOException { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - try (InputStream inputStream = url.openStream()) { + var buffer = new ByteArrayOutputStream(); + try (var inputStream = url.openStream()) { inputStream.transferTo(buffer); } buffer.flush(); diff --git a/lib/src/main/java/com/diffplug/spotless/FileSignature.java b/lib/src/main/java/com/diffplug/spotless/FileSignature.java index 59893f26e6..dfc5d89a01 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. @@ -68,7 +68,7 @@ public static FileSignature signAsSet(Iterable files) throws IOException { List natural = toSortedSet(files); List onNameOnly = toSortedSet(files, comparing(File::getName)); if (natural.size() != onNameOnly.size()) { - StringBuilder builder = new StringBuilder(); + var builder = new StringBuilder(); builder.append("For these files:\n"); for (File file : files) { builder.append(" " + file.getAbsolutePath() + "\n"); @@ -86,7 +86,7 @@ private FileSignature(final List files) throws IOException { this.files = validateInputFiles(files); this.signatures = new Sig[this.files.size()]; - int i = 0; + var i = 0; for (File file : this.files) { signatures[i] = cache.sign(file); ++i; @@ -146,13 +146,13 @@ private static final class Cache { Map cache = new HashMap<>(); synchronized Sig sign(File fileInput) throws IOException { - String canonicalPath = fileInput.getCanonicalPath(); + var canonicalPath = fileInput.getCanonicalPath(); Sig sig = cache.computeIfAbsent(canonicalPath, ThrowingEx. wrap(p -> { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - File file = new File(p); + var digest = MessageDigest.getInstance("SHA-256"); + var file = new File(p); // calculate the size and content hash of the file long size = 0; - byte[] buf = new byte[1024]; + var buf = new byte[1024]; long lastModified; try (InputStream input = new FileInputStream(file)) { lastModified = file.lastModified(); @@ -164,7 +164,7 @@ synchronized Sig sign(File fileInput) throws IOException { } return new Sig(file.getName(), size, digest.digest(), lastModified); })); - long lastModified = fileInput.lastModified(); + var lastModified = fileInput.lastModified(); if (sig.lastModified != lastModified) { cache.remove(canonicalPath); return sign(fileInput); diff --git a/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java index d9a6fe4093..1476eaad0f 100644 --- a/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-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. @@ -17,7 +17,6 @@ import java.io.File; import java.util.Objects; -import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; @@ -34,7 +33,7 @@ final class FilterByContentPatternFormatterStep extends DelegateFormatterStep { public @Nullable String format(String raw, File file) throws Exception { Objects.requireNonNull(raw, "raw"); Objects.requireNonNull(file, "file"); - Matcher matcher = contentPattern.matcher(raw); + var matcher = contentPattern.matcher(raw); if (matcher.find()) { return delegateStep.format(raw, file); } else { @@ -50,7 +49,7 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } - FilterByContentPatternFormatterStep that = (FilterByContentPatternFormatterStep) o; + var that = (FilterByContentPatternFormatterStep) o; return Objects.equals(delegateStep, that.delegateStep) && Objects.equals(contentPattern.pattern(), that.contentPattern.pattern()); } diff --git a/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java index 04a06a4673..9fd745b4aa 100644 --- a/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-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. @@ -47,7 +47,7 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } - FilterByFileFormatterStep that = (FilterByFileFormatterStep) o; + var that = (FilterByFileFormatterStep) o; return Objects.equals(delegateStep, that.delegateStep) && Objects.equals(filter, that.filter); } diff --git a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java index d1f8abd3ee..78c5d5334a 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. @@ -43,7 +43,7 @@ public class ForeignExe { /** The name of the executable, used by "where" (win) and "which" (unix). */ public static ForeignExe nameAndVersion(String exeName, String version) { - ForeignExe foreign = new ForeignExe(); + var foreign = new ForeignExe(); foreign.name = Objects.requireNonNull(exeName); foreign.version = Objects.requireNonNull(version); return foreign; @@ -105,7 +105,7 @@ public String confirmVersionAndGetAbsolutePath() throws IOException, Interrupted if (!versionMatcher.find()) { throw cantFind("Unable to parse version with /" + versionRegex + "/", cmdVersion); } - String versionFound = versionMatcher.group(1); + var versionFound = versionMatcher.group(1); if (!versionFound.equals(version)) { throw wrongVersion("You specified version " + version + ", but Spotless found " + versionFound, cmdVersion, versionFound); } @@ -122,7 +122,7 @@ private RuntimeException wrongVersion(String message, ProcessRunner.Result cmd, } private RuntimeException exceptionFmt(String msgPrimary, ProcessRunner.Result cmd, @Nullable String msgFix) { - StringBuilder errorMsg = new StringBuilder(); + var errorMsg = new StringBuilder(); errorMsg.append(msgPrimary); errorMsg.append('\n'); if (msgFix != null) { diff --git a/lib/src/main/java/com/diffplug/spotless/Formatter.java b/lib/src/main/java/com/diffplug/spotless/Formatter.java index 46793e24f6..ae4a67354d 100644 --- a/lib/src/main/java/com/diffplug/spotless/Formatter.java +++ b/lib/src/main/java/com/diffplug/spotless/Formatter.java @@ -163,12 +163,12 @@ public Formatter build() { public boolean isClean(File file) throws IOException { Objects.requireNonNull(file); - String raw = new String(Files.readAllBytes(file.toPath()), encoding); + var raw = new String(Files.readAllBytes(file.toPath()), encoding); String unix = LineEnding.toUnix(raw); // check the newlines (we can find these problems without even running the steps) - int totalNewLines = (int) unix.codePoints().filter(val -> val == '\n').count(); - int windowsNewLines = raw.length() - unix.length(); + var totalNewLines = (int) unix.codePoints().filter(val -> val == '\n').count(); + var windowsNewLines = raw.length() - unix.length(); if (lineEndingsPolicy.isUnix(file)) { if (windowsNewLines != 0) { return false; @@ -180,7 +180,7 @@ public boolean isClean(File file) throws IOException { } // check the other formats - String formatted = compute(unix, file); + var formatted = compute(unix, file); // return true iff the formatted string equals the unix one return formatted.equals(unix); @@ -200,17 +200,17 @@ public void applyTo(File file) throws IOException { public @Nullable String applyToAndReturnResultIfDirty(File file) throws IOException { Objects.requireNonNull(file); - byte[] rawBytes = Files.readAllBytes(file.toPath()); - String raw = new String(rawBytes, encoding); + var rawBytes = Files.readAllBytes(file.toPath()); + var raw = new String(rawBytes, encoding); String rawUnix = LineEnding.toUnix(raw); // enforce the format - String formattedUnix = compute(rawUnix, file); + var formattedUnix = compute(rawUnix, file); // enforce the line endings - String formatted = computeLineEndings(formattedUnix, file); + var formatted = computeLineEndings(formattedUnix, file); // write out the file iff it has changed - byte[] formattedBytes = formatted.getBytes(encoding); + var formattedBytes = formatted.getBytes(encoding); if (!Arrays.equals(rawBytes, formattedBytes)) { Files.write(file.toPath(), formattedBytes, StandardOpenOption.TRUNCATE_EXISTING); return formattedUnix; @@ -257,7 +257,7 @@ public String compute(String unix, File file) { exceptionPolicy.handleError(e, step, ""); } else { // Path may be forged from a different FileSystem than Filesystem.default - String relativePath = rootDir.relativize(rootDir.getFileSystem().getPath(file.getPath())).toString(); + var relativePath = rootDir.relativize(rootDir.getFileSystem().getPath(file.getPath())).toString(); exceptionPolicy.handleError(e, step, relativePath); } } @@ -267,8 +267,8 @@ public String compute(String unix, File file) { @Override public int hashCode() { - final int prime = 31; - int result = 1; + final var prime = 31; + var result = 1; result = prime * result + name.hashCode(); result = prime * result + encoding.hashCode(); result = prime * result + lineEndingsPolicy.hashCode(); @@ -289,7 +289,7 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } - Formatter other = (Formatter) obj; + var other = (Formatter) obj; return name.equals(other.name) && encoding.equals(other.encoding) && lineEndingsPolicy.equals(other.lineEndingsPolicy) && diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java b/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java index 81fa6a93cf..f2142cbad7 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. @@ -29,7 +29,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -70,7 +69,7 @@ public static FormatterProperties from(File... files) throws IllegalArgumentExce */ public static FormatterProperties from(Iterable files) throws IllegalArgumentException { List nonNullFiles = toNullHostileList(files); - FormatterProperties properties = new FormatterProperties(); + var properties = new FormatterProperties(); nonNullFiles.forEach(properties::add); return properties; } @@ -87,15 +86,15 @@ public static FormatterProperties from(Iterable files) throws IllegalArgum private void add(final File settingsFile) throws IllegalArgumentException { Objects.requireNonNull(settingsFile); if (!(settingsFile.isFile() && settingsFile.canRead())) { - String msg = String.format("Settings file '%s' does not exist or can not be read.", settingsFile); + var msg = String.format("Settings file '%s' does not exist or can not be read.", settingsFile); throw new IllegalArgumentException(msg); } try { - Properties newSettings = FileParser.parse(settingsFile); + var newSettings = FileParser.parse(settingsFile); properties.putAll(newSettings); } catch (IOException | IllegalArgumentException exception) { - String message = String.format("Failed to add properties from '%s' to formatter settings.", settingsFile); - String detailedMessage = exception.getMessage(); + var message = String.format("Failed to add properties from '%s' to formatter settings.", settingsFile); + var detailedMessage = exception.getMessage(); if (null != detailedMessage) { message += String.format(" %s", detailedMessage); } @@ -112,7 +111,7 @@ private enum FileParser { LINE_ORIENTED("properties", "prefs") { @Override protected Properties execute(final File file) throws IOException, IllegalArgumentException { - Properties properties = new Properties(); + var properties = new Properties(); try (InputStream inputProperties = new FileInputStream(file)) { properties.load(inputProperties); } @@ -133,7 +132,7 @@ protected Properties execute(final File file) throws IOException, IllegalArgumen private Node getRootNode(final File file) throws IOException, IllegalArgumentException { try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + var dbf = DocumentBuilderFactory.newInstance(); /* * It is not required to validate or normalize attribute values for * the XMLs currently supported. Disabling validation is supported by @@ -144,7 +143,7 @@ private Node getRootNode(final File file) throws IOException, IllegalArgumentExc * catalog and provision of the SUN preperties.dtd. */ dbf.setFeature(LOAD_EXTERNAL_DTD_PROP, false); - DocumentBuilder db = dbf.newDocumentBuilder(); + var db = dbf.newDocumentBuilder(); return db.parse(file).getDocumentElement(); } catch (SAXException | ParserConfigurationException e) { throw new IllegalArgumentException("File has no valid XML syntax.", e); @@ -166,13 +165,13 @@ private Node getRootNode(final File file) throws IOException, IllegalArgumentExc protected abstract Properties execute(File file) throws IOException, IllegalArgumentException; public static Properties parse(final File file) throws IOException, IllegalArgumentException { - String fileNameExtension = getFileNameExtension(file); + var fileNameExtension = getFileNameExtension(file); for (FileParser parser : FileParser.values()) { if (parser.supportedFileNameExtensions.contains(fileNameExtension)) { return parser.execute(file); } } - String msg = String.format( + var msg = String.format( "The file name extension '%1$s' is not part of the supported file extensions [%2$s].", fileNameExtension, Arrays.toString(FileParser.values())); throw new IllegalArgumentException(msg); @@ -180,8 +179,8 @@ public static Properties parse(final File file) throws IOException, IllegalArgum } private static String getFileNameExtension(File file) { - String fileName = file.getName(); - int seperatorPos = fileName.lastIndexOf(FILE_EXTENSION_SEPARATOR); + var fileName = file.getName(); + var seperatorPos = fileName.lastIndexOf(FILE_EXTENSION_SEPARATOR); return 0 > seperatorPos ? "" : fileName.substring(seperatorPos + 1); } @@ -192,7 +191,7 @@ private enum XmlParser { @Override protected Properties execute(final File xmlFile, final Node rootNode) throws IOException, IllegalArgumentException { - final Properties properties = new Properties(); + final var properties = new Properties(); try (InputStream xmlInput = new FileInputStream(xmlFile)) { properties.loadFromXML(xmlInput); } @@ -203,7 +202,7 @@ protected Properties execute(final File xmlFile, final Node rootNode) PROFILES("profiles") { @Override protected Properties execute(File file, Node rootNode) throws IOException, IllegalArgumentException { - final Properties properties = new Properties(); + final var properties = new Properties(); Node firstProfile = getSingleProfile(rootNode); for (Object settingObj : getChildren(firstProfile, "setting")) { Node setting = (Node) settingObj; @@ -230,7 +229,7 @@ private Node getSingleProfile(final Node rootNode) throws IllegalArgumentExcepti throw new IllegalArgumentException("The formatter configuration profile files does not contain any 'profile' elements."); } if (profiles.size() > 1) { - String message = "Formatter configuration file contains multiple profiles: ["; + var message = "Formatter configuration file contains multiple profiles: ["; message += profiles.stream().map(XmlParser::getProfileName).collect(Collectors.joining("; ")); message += "]%n The formatter can only cope with a single profile per configuration file. Please remove the other profiles."; throw new IllegalArgumentException(message); @@ -274,7 +273,7 @@ public static Properties parse(final File file, final Node rootNode) return parser.execute(file, rootNode); } } - String msg = String.format("The XML root node '%1$s' is not part of the supported root nodes [%2$s].", + var msg = String.format("The XML root node '%1$s' is not part of the supported root nodes [%2$s].", rootNodeName, Arrays.toString(XmlParser.values())); throw new IllegalArgumentException(msg); } diff --git a/lib/src/main/java/com/diffplug/spotless/Jvm.java b/lib/src/main/java/com/diffplug/spotless/Jvm.java index 7c9ad5b47a..f5b6fe978f 100644 --- a/lib/src/main/java/com/diffplug/spotless/Jvm.java +++ b/lib/src/main/java/com/diffplug/spotless/Jvm.java @@ -23,7 +23,6 @@ import java.util.NavigableMap; import java.util.Objects; import java.util.TreeMap; -import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -36,11 +35,11 @@ public final class Jvm { private static final int VERSION; static { - String jre = System.getProperty("java.version"); + var jre = System.getProperty("java.version"); if (jre.startsWith("1.8")) { VERSION = 8; } else { - Matcher matcher = Pattern.compile("(\\d+)").matcher(jre); + var matcher = Pattern.compile("(\\d+)").matcher(jre); if (!matcher.find()) { throw new IllegalArgumentException("Expected " + jre + " to start with an integer"); } @@ -120,13 +119,13 @@ private void verifyVersionRangesDoNotIntersect(NavigableMap jvm2fmtV /** @return Highest formatter version recommended for this JVM (null, if JVM not supported) */ @Nullable public V getRecommendedFormatterVersion() { - Integer configuredJvmVersionOrNull = jvm2fmtMaxVersion.floorKey(Jvm.version()); + var configuredJvmVersionOrNull = jvm2fmtMaxVersion.floorKey(Jvm.version()); return (null == configuredJvmVersionOrNull) ? null : jvm2fmtMaxVersion.get(configuredJvmVersionOrNull); } @Nullable public V getMinimumRequiredFormatterVersion() { - Integer configuredJvmVersionOrNull = jvm2fmtMinVersion.floorKey(Jvm.version()); + var configuredJvmVersionOrNull = jvm2fmtMinVersion.floorKey(Jvm.version()); return (null == configuredJvmVersionOrNull) ? null : jvm2fmtMinVersion.get(configuredJvmVersionOrNull); } @@ -137,7 +136,7 @@ public V getMinimumRequiredFormatterVersion() { */ public void assertFormatterSupported(V formatterVersion) { Objects.requireNonNull(formatterVersion); - String error = buildUnsupportedFormatterMessage(formatterVersion); + var error = buildUnsupportedFormatterMessage(formatterVersion); if (!error.isEmpty()) { throw new IllegalArgumentException(error); } @@ -145,12 +144,12 @@ public void assertFormatterSupported(V formatterVersion) { private String buildUnsupportedFormatterMessage(V fmtVersion) { // check if the jvm version is to low for the formatter version - int requiredJvmVersion = getRequiredJvmVersion(fmtVersion); + var requiredJvmVersion = getRequiredJvmVersion(fmtVersion); if (Jvm.version() < requiredJvmVersion) { return buildUpgradeJvmMessage(fmtVersion) + "Upgrade your JVM or try " + toString(); } // check if the formatter version is too low for the jvm version - V minimumFormatterVersion = getMinimumRequiredFormatterVersion(); + var minimumFormatterVersion = getMinimumRequiredFormatterVersion(); if ((null != minimumFormatterVersion) && (fmtVersionComparator.compare(fmtVersion, minimumFormatterVersion) < 0)) { return String.format("You are running Spotless on JVM %d. This requires %s of at least %s (you are using %s).%n", Jvm.version(), fmtName, minimumFormatterVersion, fmtVersion); } @@ -159,9 +158,9 @@ private String buildUnsupportedFormatterMessage(V fmtVersion) { } private String buildUpgradeJvmMessage(V fmtVersion) { - StringBuilder builder = new StringBuilder(); + var builder = new StringBuilder(); builder.append(String.format("You are running Spotless on JVM %d", Jvm.version())); - V recommendedFmtVersionOrNull = getRecommendedFormatterVersion(); + var recommendedFmtVersionOrNull = getRecommendedFormatterVersion(); if (null != recommendedFmtVersionOrNull) { builder.append(String.format(", which limits you to %s %s.%n", fmtName, recommendedFmtVersionOrNull)); } else { @@ -180,7 +179,7 @@ private int getRequiredJvmVersion(V fmtVersion) { entry = fmtMaxVersion2jvmVersion.lastEntry(); } if (null != entry) { - V maxKnownFmtVersion = jvm2fmtMaxVersion.get(entry.getValue()); + var maxKnownFmtVersion = jvm2fmtMaxVersion.get(entry.getValue()); if (fmtVersionComparator.compare(fmtVersion, maxKnownFmtVersion) <= 0) { return entry.getValue(); } @@ -197,8 +196,8 @@ private int getRequiredJvmVersion(V fmtVersion) { public FormatterFunc suggestLaterVersionOnError(V formatterVersion, FormatterFunc originalFunc) { Objects.requireNonNull(formatterVersion); Objects.requireNonNull(originalFunc); - final String hintUnsupportedProblem = buildUnsupportedFormatterMessage(formatterVersion); - final String proposeDifferentFormatter = hintUnsupportedProblem.isEmpty() ? buildUpgradeFormatterMessage(formatterVersion) : hintUnsupportedProblem; + final var hintUnsupportedProblem = buildUnsupportedFormatterMessage(formatterVersion); + final var proposeDifferentFormatter = hintUnsupportedProblem.isEmpty() ? buildUpgradeFormatterMessage(formatterVersion) : hintUnsupportedProblem; return proposeDifferentFormatter.isEmpty() ? originalFunc : new FormatterFunc() { @Override @@ -223,10 +222,10 @@ public String apply(String input) throws Exception { } private String buildUpgradeFormatterMessage(V fmtVersion) { - StringBuilder builder = new StringBuilder(); + var builder = new StringBuilder(); // check if the formatter is not supported on this jvm - V minimumFormatterVersion = getMinimumRequiredFormatterVersion(); - V recommendedFmtVersionOrNull = getRecommendedFormatterVersion(); + var minimumFormatterVersion = getMinimumRequiredFormatterVersion(); + var recommendedFmtVersionOrNull = getRecommendedFormatterVersion(); if ((null != minimumFormatterVersion) && (fmtVersionComparator.compare(fmtVersion, minimumFormatterVersion) < 0)) { builder.append(String.format("You are running Spotless on JVM %d. This requires %s of at least %s.%n", Jvm.version(), fmtName, minimumFormatterVersion)); builder.append(String.format("You are using %s %s.%n", fmtName, fmtVersion)); @@ -242,7 +241,7 @@ private String buildUpgradeFormatterMessage(V fmtVersion) { V higherFormatterVersionOrNull = fmtMaxVersion2jvmVersion.higherKey(fmtVersion); if (null != higherFormatterVersionOrNull) { builder.append(buildUpgradeJvmMessage(fmtVersion)); - Integer higherJvmVersion = fmtMaxVersion2jvmVersion.get(higherFormatterVersionOrNull); + var higherJvmVersion = fmtMaxVersion2jvmVersion.get(higherFormatterVersionOrNull); builder.append(String.format("If you upgrade your JVM to %d+, then you can use %s %s, which may have fixed this problem.", higherJvmVersion, fmtName, higherFormatterVersionOrNull)); } } @@ -263,12 +262,12 @@ private static class SemanticVersionComparator implements Comparator { public int compare(V version0, V version1) { Objects.requireNonNull(version0); Objects.requireNonNull(version1); - int[] version0Items = convert(version0); - int[] version1Items = convert(version1); - int numberOfElements = version0Items.length > version1Items.length ? version0Items.length : version1Items.length; + var version0Items = convert(version0); + var version1Items = convert(version1); + var numberOfElements = version0Items.length > version1Items.length ? version0Items.length : version1Items.length; version0Items = Arrays.copyOf(version0Items, numberOfElements); version1Items = Arrays.copyOf(version1Items, numberOfElements); - for (int i = 0; i < numberOfElements; i++) { + for (var i = 0; i < numberOfElements; i++) { if (version0Items[i] > version1Items[i]) { return 1; } else if (version1Items[i] > version0Items[i]) { diff --git a/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java b/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java index e2d6ba8988..d6e5a99ea1 100644 --- a/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java +++ b/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.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. @@ -103,8 +103,8 @@ public final int hashCode() { } static byte[] toBytes(Serializable obj) { - ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); - try (ObjectOutputStream objectOutput = new ObjectOutputStream(byteOutput)) { + var byteOutput = new ByteArrayOutputStream(); + try (var objectOutput = new ObjectOutputStream(byteOutput)) { objectOutput.writeObject(obj); } catch (IOException e) { throw ThrowingEx.asRuntime(e); diff --git a/lib/src/main/java/com/diffplug/spotless/LineEnding.java b/lib/src/main/java/com/diffplug/spotless/LineEnding.java index 72b2532f2a..80fbba7083 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. @@ -17,7 +17,6 @@ import java.io.File; import java.io.Serializable; -import java.lang.reflect.Method; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Supplier; @@ -57,7 +56,7 @@ public Policy createPolicy(File projectDir, Supplier> toFormat) { if (gitAttributesPolicyCreator == null) { try { Class clazz = Class.forName("com.diffplug.spotless.extra.GitAttributesLineEndings"); - Method method = clazz.getMethod("create", File.class, Supplier.class); + var method = clazz.getMethod("create", File.class, Supplier.class); gitAttributesPolicyCreator = (proj, target) -> ThrowingEx.get(() -> (Policy) method.invoke(null, proj, target)); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) { throw new IllegalStateException("LineEnding.GIT_ATTRIBUTES requires the spotless-lib-extra library, but it is not on the classpath", e); @@ -135,14 +134,14 @@ public interface Policy extends Serializable, NoLambda { /** Returns true iff this file has unix line endings. */ public default boolean isUnix(File file) { Objects.requireNonNull(file); - String ending = getEndingFor(file); + var ending = getEndingFor(file); return ending.equals(UNIX.str()); } } /** Returns a string with exclusively unix line endings. */ public static String toUnix(String input) { - int lastCarriageReturn = input.lastIndexOf('\r'); + var lastCarriageReturn = input.lastIndexOf('\r'); if (lastCarriageReturn == -1) { return input; } else { diff --git a/lib/src/main/java/com/diffplug/spotless/MoreIterables.java b/lib/src/main/java/com/diffplug/spotless/MoreIterables.java index c3b0e5f286..9739ebb897 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. @@ -51,9 +51,9 @@ static List toSortedSet(Iterable raw, Comparator comparator) { // remove any duplicates (normally there won't be any) if (toBeSorted.size() > 1) { Iterator iter = toBeSorted.iterator(); - T last = iter.next(); + var last = iter.next(); while (iter.hasNext()) { - T next = iter.next(); + var next = iter.next(); if (comparator.compare(next, last) == 0) { iter.remove(); } else { diff --git a/lib/src/main/java/com/diffplug/spotless/NoLambda.java b/lib/src/main/java/com/diffplug/spotless/NoLambda.java index ce326a6ceb..353914e2be 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. @@ -61,7 +61,7 @@ public boolean equals(Object otherObj) { if (otherObj == null) { return false; } else if (otherObj.getClass().equals(this.getClass())) { - EqualityBasedOnSerialization other = (EqualityBasedOnSerialization) otherObj; + var other = (EqualityBasedOnSerialization) otherObj; return Arrays.equals(toBytes(), other.toBytes()); } else { return false; diff --git a/lib/src/main/java/com/diffplug/spotless/PaddedCell.java b/lib/src/main/java/com/diffplug/spotless/PaddedCell.java index 91914b7908..5717d2bcd5 100644 --- a/lib/src/main/java/com/diffplug/spotless/PaddedCell.java +++ b/lib/src/main/java/com/diffplug/spotless/PaddedCell.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. @@ -89,7 +89,7 @@ public static PaddedCell check(Formatter formatter, File file) { Objects.requireNonNull(formatter, "formatter"); Objects.requireNonNull(file, "file"); byte[] rawBytes = ThrowingEx.get(() -> Files.readAllBytes(file.toPath())); - String raw = new String(rawBytes, formatter.getEncoding()); + var raw = new String(rawBytes, formatter.getEncoding()); String original = LineEnding.toUnix(raw); return check(formatter, file, original, MAX_CYCLE); } @@ -121,13 +121,13 @@ private static PaddedCell check(Formatter formatter, File file, String original, List appliedN = new ArrayList<>(); appliedN.add(appliedOnce); appliedN.add(appliedTwice); - String input = appliedTwice; + var input = appliedTwice; while (appliedN.size() < maxLength) { String output = formatter.compute(input, file); if (output.equals(input)) { return Type.CONVERGE.create(file, appliedN); } else { - int idx = appliedN.indexOf(output); + var idx = appliedN.indexOf(output); if (idx >= 0) { return Type.CYCLE.create(file, appliedN.subList(idx, appliedN.size())); } else { @@ -144,7 +144,7 @@ private static PaddedCell check(Formatter formatter, File file, String original, * (did not converge after a single iteration). */ public boolean misbehaved() { - boolean isWellBehaved = type == Type.CONVERGE && steps.size() <= 1; + var isWellBehaved = type == Type.CONVERGE && steps.size() <= 1; return !isWellBehaved; } @@ -186,12 +186,12 @@ public static DirtyState calculateDirtyState(Formatter formatter, File file) thr Objects.requireNonNull(formatter, "formatter"); Objects.requireNonNull(file, "file"); - byte[] rawBytes = Files.readAllBytes(file.toPath()); + var rawBytes = Files.readAllBytes(file.toPath()); return calculateDirtyState(formatter, file, rawBytes); } public static DirtyState calculateDirtyState(Formatter formatter, File file, byte[] rawBytes) throws IOException { - String raw = new String(rawBytes, formatter.getEncoding()); + var raw = new String(rawBytes, formatter.getEncoding()); // check that all characters were encodable String encodingError = EncodingErrorMsg.msg(raw, rawBytes, formatter.getEncoding()); if (encodingError != null) { @@ -223,7 +223,7 @@ public static DirtyState calculateDirtyState(Formatter formatter, File file, byt } // get the canonical bytes - String canonicalUnix = cell.canonical(); + var canonicalUnix = cell.canonical(); String canonical = formatter.computeLineEndings(canonicalUnix, file); byte[] canonicalBytes = canonical.getBytes(formatter.getEncoding()); if (!Arrays.equals(rawBytes, canonicalBytes)) { diff --git a/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java b/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java index 4e48042184..c7fd94848b 100644 --- a/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java +++ b/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java @@ -111,7 +111,7 @@ public Result exec(@Nullable byte[] stdin, List args) throws IOException /** Creates a process with the given arguments, the given byte array is written to stdin immediately. */ public Result exec(@Nullable File cwd, @Nullable Map environment, @Nullable byte[] stdin, List args) throws IOException, InterruptedException { - LongRunningProcess process = start(cwd, environment, stdin, args); + var process = start(cwd, environment, stdin, args); try { // wait for the process to finish process.waitFor(); @@ -141,7 +141,7 @@ public LongRunningProcess start(@Nullable File cwd, @Nullable Map environment, @Nullable byte[] stdin, boolean redirectErrorStream, List args) throws IOException { checkState(); - ProcessBuilder builder = new ProcessBuilder(args); + var builder = new ProcessBuilder(args); if (cwd != null) { builder.directory(cwd); } @@ -155,7 +155,7 @@ public LongRunningProcess start(@Nullable File cwd, @Nullable Map outputFut = threadStdOut.submit(() -> drainToBytes(process.getInputStream(), bufStdOut)); Future errorFut = null; if (!redirectErrorStream) { @@ -168,7 +168,7 @@ public LongRunningProcess start(@Nullable File cwd, @Nullable Map arguments: " + args + "\n"); builder.append("> exit code: " + exitCode + "\n"); BiConsumer perStream = (name, content) -> { - String string = new String(content, Charset.defaultCharset()).trim(); + var string = new String(content, Charset.defaultCharset()).trim(); if (string.isEmpty()) { builder.append("> " + name + ": (empty)\n"); } else { - String[] lines = string.replace("\r", "").split("\n"); + var lines = string.replace("\r", "").split("\n"); if (lines.length == 1) { builder.append("> " + name + ": " + lines[0] + "\n"); } else { @@ -345,7 +345,7 @@ public boolean isAlive() { } public Result result() throws ExecutionException, InterruptedException { - int exitCode = waitFor(); + var exitCode = waitFor(); return new Result(args, exitCode, this.outputFut.get(), (this.errorFut != null ? this.errorFut.get() : null)); } diff --git a/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java b/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java index da4fc6aa04..931fee7d40 100644 --- a/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java +++ b/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java @@ -62,7 +62,7 @@ public synchronized void write(int b) { @Override public synchronized void write(byte[] b, int off, int len) { - int remaining = limit - count; + var remaining = limit - count; if (remaining >= len) { super.write(b, off, len); return; @@ -77,7 +77,7 @@ public synchronized void write(byte[] b, int off, int len) { // we are over the limit isOverLimit = true; // write till limit is reached - int writeTillLimit = Math.min(len, limit - zeroIndexPointer); + var writeTillLimit = Math.min(len, limit - zeroIndexPointer); System.arraycopy(b, off, buf, zeroIndexPointer, writeTillLimit); zeroIndexPointer = (zeroIndexPointer + writeTillLimit) % limit; if (writeTillLimit < len) { @@ -109,7 +109,7 @@ public synchronized byte[] toByteArray() { if (!isOverLimit) { return super.toByteArray(); } - byte[] result = new byte[limit]; + var result = new byte[limit]; System.arraycopy(buf, zeroIndexPointer, result, 0, limit - zeroIndexPointer); System.arraycopy(buf, 0, result, limit - zeroIndexPointer, zeroIndexPointer); return result; diff --git a/lib/src/main/java/com/diffplug/spotless/SerializableFileFilterImpl.java b/lib/src/main/java/com/diffplug/spotless/SerializableFileFilterImpl.java index f3a8f1f18d..aeb1fe99c6 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. @@ -36,7 +36,7 @@ static class SkipFilesNamed extends NoLambda.EqualityBasedOnSerialization implem @Override public boolean accept(File pathname) { - String name = pathname.getName(); + var name = pathname.getName(); return Arrays.stream(namesToSkip).noneMatch(name::equals); } } diff --git a/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java b/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java index 237e326482..437f288b0b 100644 --- a/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java +++ b/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java @@ -71,7 +71,7 @@ synchronized ClassLoader classloader(JarState state) { @SuppressFBWarnings("DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED") synchronized ClassLoader classloader(Serializable key, JarState state) { - SerializedKey serializedKey = new SerializedKey(key); + var serializedKey = new SerializedKey(key); return cache .computeIfAbsent(serializedKey, k -> { LOGGER.debug("Allocating an additional FeatureClassLoader for key={} Cache.size was {}", key, cache.size()); diff --git a/lib/src/main/java/com/diffplug/spotless/ThrowingEx.java b/lib/src/main/java/com/diffplug/spotless/ThrowingEx.java index f664c62bf3..67e566f1ee 100644 --- a/lib/src/main/java/com/diffplug/spotless/ThrowingEx.java +++ b/lib/src/main/java/com/diffplug/spotless/ThrowingEx.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-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. @@ -105,7 +105,7 @@ public static RuntimeException asRuntime(Exception e) { * } */ public static RuntimeException unwrapCause(Throwable e) { - Throwable cause = e.getCause(); + var cause = e.getCause(); if (cause == null) { return asRuntimeRethrowError(e); } else { diff --git a/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4FormatterStep.java b/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4FormatterStep.java index d71182c65d..2f58c0cff8 100644 --- a/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4FormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4FormatterStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-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. @@ -18,7 +18,6 @@ import java.io.IOException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import com.diffplug.spotless.*; @@ -60,7 +59,7 @@ FormatterFunc createFormat() throws ClassNotFoundException, NoSuchMethodExceptio // String Antlr4Formatter::format(String input) Class formatter = classLoader.loadClass("com.khubla.antlr4formatter.Antlr4Formatter"); - Method formatterMethod = formatter.getMethod("format", String.class); + var formatterMethod = formatter.getMethod("format", String.class); return input -> { try { diff --git a/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java b/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java index 5591045505..1c1b544c25 100644 --- a/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-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. @@ -68,7 +68,7 @@ public FormatterStep create() { } private State createState() throws IOException, InterruptedException { - String howToInstall = "" + + var howToInstall = "" + "You can download clang-format from https://releases.llvm.org and " + "then point Spotless to it with {@code pathToExe('/path/to/clang-format')} " + "or you can use your platform's package manager:" + @@ -110,7 +110,7 @@ String format(ProcessRunner runner, String input, File file) throws IOException, } args = tmpArgs; } - final String[] processArgs = args.toArray(new String[args.size() + 1]); + final var processArgs = args.toArray(new String[args.size() + 1]); processArgs[processArgs.length - 1] = "--assume-filename=" + file.getName(); return runner.exec(input.getBytes(StandardCharsets.UTF_8), processArgs).assertExitZero(StandardCharsets.UTF_8); } diff --git a/lib/src/main/java/com/diffplug/spotless/generic/EndWithNewlineStep.java b/lib/src/main/java/com/diffplug/spotless/generic/EndWithNewlineStep.java index bd9a93a6e8..04549263d6 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/EndWithNewlineStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/EndWithNewlineStep.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. @@ -35,7 +35,7 @@ private static String format(String rawUnix) { } // find the last character which has real content - int lastContentCharacter = rawUnix.length() - 1; + var lastContentCharacter = rawUnix.length() - 1; char c; while (lastContentCharacter >= 0) { c = rawUnix.charAt(lastContentCharacter); @@ -52,7 +52,7 @@ private static String format(String rawUnix) { } else if (lastContentCharacter == rawUnix.length() - 2 && rawUnix.charAt(rawUnix.length() - 1) == '\n') { return rawUnix; } else { - StringBuilder builder = new StringBuilder(lastContentCharacter + 2); + var builder = new StringBuilder(lastContentCharacter + 2); builder.append(rawUnix, 0, lastContentCharacter + 1); builder.append('\n'); return builder.toString(); diff --git a/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java b/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java index 4281df736c..095203b503 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-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. @@ -81,10 +81,10 @@ static class Runtime { String format(String raw) { // reset the buffer builder.setLength(0); - int lineStart = 0; // beginning of line + var lineStart = 0; // beginning of line do { - int contentStart = lineStart; // beginning of non-whitespace - int numSpaces = 0; + var contentStart = lineStart; // beginning of non-whitespace + var numSpaces = 0; char c; while (contentStart < raw.length() && isSpaceOrTab(c = raw.charAt(contentStart))) { switch (c) { @@ -101,18 +101,18 @@ String format(String raw) { } // detect potential multi-line comments - boolean mightBeMultiLineComment = (contentStart < raw.length()) && (raw.charAt(contentStart) == '*'); + var mightBeMultiLineComment = (contentStart < raw.length()) && (raw.charAt(contentStart) == '*'); // add the leading space in a canonical way if (numSpaces > 0) { switch (state.type) { case SPACE: - for (int i = 0; i < numSpaces; ++i) { + for (var i = 0; i < numSpaces; ++i) { builder.append(' '); } break; case TAB: - for (int i = 0; i < numSpaces / state.numSpacesPerTab; ++i) { + for (var i = 0; i < numSpaces / state.numSpacesPerTab; ++i) { builder.append('\t'); } if (mightBeMultiLineComment && (numSpaces % state.numSpacesPerTab == 1)) { diff --git a/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java b/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java index 90f57b24ef..4c89ff6b24 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java @@ -1,5 +1,5 @@ /* - * Copyright 2021 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. @@ -19,7 +19,6 @@ import java.util.Objects; import java.util.stream.Collectors; -import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import com.diffplug.spotless.FormatterFunc; @@ -60,7 +59,7 @@ FormatterFunc toFormatter() { } else { scriptEngineManager = new ScriptEngineManager(jarState.getClassLoader()); } - ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(engine); + var scriptEngine = scriptEngineManager.getEngineByName(engine); if (scriptEngine == null) { throw new IllegalArgumentException("Unknown script engine '" + engine + "'. Available engines: " + diff --git a/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java b/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java index 073af855d3..3340f76236 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java @@ -26,7 +26,6 @@ import java.util.Objects; import java.util.Optional; import java.util.function.Supplier; -import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; @@ -123,8 +122,8 @@ public FormatterStep build() { if (yearMode.get() == YearMode.SET_FROM_GIT) { formatterStep = FormatterStep.createNeverUpToDateLazy(name, () -> { - boolean updateYear = false; // doesn't matter - Runtime runtime = new Runtime(headerLazy.get(), delimiter, yearSeparator, updateYear, skipLinesMatching); + var updateYear = false; // doesn't matter + var runtime = new Runtime(headerLazy.get(), delimiter, yearSeparator, updateYear, skipLinesMatching); return FormatterFunc.needsFile(runtime::setLicenseHeaderYearsFromGitHistory); }); } else { @@ -235,17 +234,17 @@ private Runtime(String licenseHeader, String delimiter, String yearSeparator, bo Optional yearToken = getYearToken(licenseHeader); if (yearToken.isPresent()) { this.yearToday = String.valueOf(YearMonth.now().getYear()); - int yearTokenIndex = licenseHeader.indexOf(yearToken.get()); + var yearTokenIndex = licenseHeader.indexOf(yearToken.get()); this.beforeYear = licenseHeader.substring(0, yearTokenIndex); this.afterYear = licenseHeader.substring(yearTokenIndex + yearToken.get().length()); this.yearSepOrFull = yearSeparator; this.updateYearWithLatest = updateYearWithLatest; - boolean hasHeaderWithRange = false; - int yearPlusSep = 4 + yearSeparator.length(); + var hasHeaderWithRange = false; + var yearPlusSep = 4 + yearSeparator.length(); if (beforeYear.endsWith(yearSeparator) && yearTokenIndex > yearPlusSep) { // year from in range - String yearFrom = licenseHeader.substring(yearTokenIndex - yearPlusSep, yearTokenIndex).substring(0, 4); + var yearFrom = licenseHeader.substring(yearTokenIndex - yearPlusSep, yearTokenIndex).substring(0, 4); hasHeaderWithRange = YYYY.matcher(yearFrom).matches(); } this.licenseHeaderWithRange = hasHeaderWithRange; @@ -275,13 +274,13 @@ private String format(String raw, File file) { if (skipLinesMatching == null) { return addOrUpdateLicenseHeader(raw, file); } else { - String[] lines = raw.split("\n"); - StringBuilder skippedLinesBuilder = new StringBuilder(); - StringBuilder remainingLinesBuilder = new StringBuilder(); - boolean lastMatched = true; + var lines = raw.split("\n"); + var skippedLinesBuilder = new StringBuilder(); + var remainingLinesBuilder = new StringBuilder(); + var lastMatched = true; for (String line : lines) { if (lastMatched) { - Matcher matcher = skipLinesMatching.matcher(line); + var matcher = skipLinesMatching.matcher(line); if (matcher.find()) { skippedLinesBuilder.append(line).append('\n'); } else { @@ -303,11 +302,11 @@ private String addOrUpdateLicenseHeader(String raw, File file) { } private String replaceYear(String raw) { - Matcher contentMatcher = delimiterPattern.matcher(raw); + var contentMatcher = delimiterPattern.matcher(raw); if (!contentMatcher.find()) { throw new IllegalArgumentException("Unable to find delimiter regex " + delimiterPattern); } else { - String content = raw.substring(contentMatcher.start()); + var content = raw.substring(contentMatcher.start()); if (yearToday == null) { // the no year case is easy if (contentMatcher.start() == yearSepOrFull.length() && raw.startsWith(yearSepOrFull)) { @@ -320,23 +319,23 @@ private String replaceYear(String raw) { } } else { // the yes year case is a bit harder - int beforeYearIdx = raw.indexOf(beforeYear); - int afterYearIdx = raw.indexOf(afterYear, beforeYearIdx + beforeYear.length() + 1); + var beforeYearIdx = raw.indexOf(beforeYear); + var afterYearIdx = raw.indexOf(afterYear, beforeYearIdx + beforeYear.length() + 1); if (beforeYearIdx >= 0 && afterYearIdx >= 0 && afterYearIdx + afterYear.length() <= contentMatcher.start()) { // and also ends with exactly the right header, so it's easy to parse the existing year - String existingYear = raw.substring(beforeYearIdx + beforeYear.length(), afterYearIdx); - String newYear = calculateYearExact(existingYear); + var existingYear = raw.substring(beforeYearIdx + beforeYear.length(), afterYearIdx); + var newYear = calculateYearExact(existingYear); if (existingYear.equals(newYear)) { // fastpath where we don't need to make any changes at all - boolean noPadding = beforeYearIdx == 0 && afterYearIdx + afterYear.length() == contentMatcher.start(); // allows fastpath return raw + var noPadding = beforeYearIdx == 0 && afterYearIdx + afterYear.length() == contentMatcher.start(); // allows fastpath return raw if (noPadding) { return raw; } } return beforeYear + newYear + afterYear + content; } else { - String newYear = calculateYearBySearching(raw.substring(0, contentMatcher.start())); + var newYear = calculateYearBySearching(raw.substring(0, contentMatcher.start())); // at worst, we just say that it was made today return beforeYear + newYear + afterYear + content; } @@ -368,20 +367,20 @@ private String calculateYearExact(String parsedYear) { /** Searches the given string for YYYY, and uses that to determine the year range. */ private String calculateYearBySearching(String content) { - Matcher yearMatcher = YYYY.matcher(content); + var yearMatcher = YYYY.matcher(content); if (yearMatcher.find()) { - String firstYear = yearMatcher.group(); + var firstYear = yearMatcher.group(); String secondYear = null; if (updateYearWithLatest) { secondYear = firstYear.equals(yearToday) ? null : yearToday; } else { - String contentWithSecondYear = content.substring(yearMatcher.end() + 1); - int endOfLine = contentWithSecondYear.indexOf('\n'); + var contentWithSecondYear = content.substring(yearMatcher.end() + 1); + var endOfLine = contentWithSecondYear.indexOf('\n'); if (endOfLine != -1) { contentWithSecondYear = contentWithSecondYear.substring(0, endOfLine); } - Matcher secondYearMatcher = YYYY.matcher(contentWithSecondYear); + var secondYearMatcher = YYYY.matcher(contentWithSecondYear); if (secondYearMatcher.find()) { secondYear = secondYearMatcher.group(); } @@ -408,7 +407,7 @@ private String setLicenseHeaderYearsFromGitHistory(String raw, File file) throws if (yearToday == null) { return raw; } - Matcher contentMatcher = delimiterPattern.matcher(raw); + var contentMatcher = delimiterPattern.matcher(raw); if (!contentMatcher.find()) { throw new IllegalArgumentException("Unable to find delimiter regex " + delimiterPattern); } @@ -422,7 +421,7 @@ private String setLicenseHeaderYearsFromGitHistory(String raw, File file) throws // we'll settle for just the most recent, even if it was just a modification. oldYear = parseYear("git log --follow --find-renames=40% --reverse", file); } - String newYear = parseYear("git log --max-count=1", file); + var newYear = parseYear("git log --max-count=1", file); String yearRange; if (oldYear.equals(newYear)) { yearRange = oldYear; @@ -436,30 +435,30 @@ private String replaceFileName(String raw, File file) { if (!hasFileToken) { return raw; } - Matcher contentMatcher = delimiterPattern.matcher(raw); + var contentMatcher = delimiterPattern.matcher(raw); if (!contentMatcher.find()) { throw new IllegalArgumentException("Unable to find delimiter regex " + delimiterPattern); } - String header = raw.substring(0, contentMatcher.start()); - String content = raw.substring(contentMatcher.start()); + var header = raw.substring(0, contentMatcher.start()); + var content = raw.substring(contentMatcher.start()); return FILENAME_PATTERN.matcher(header).replaceAll(file.getName()) + content; } private static String parseYear(String cmd, File file) throws IOException { - String fullCmd = cmd + " -- " + file.getAbsolutePath(); - ProcessBuilder builder = new ProcessBuilder().directory(file.getParentFile()); + var fullCmd = cmd + " -- " + file.getAbsolutePath(); + var builder = new ProcessBuilder().directory(file.getParentFile()); if (FileSignature.machineIsWin()) { builder.command("cmd", "/c", fullCmd); } else { builder.command("bash", "-c", fullCmd); } - Process process = builder.start(); - String output = drain(process.getInputStream()); - String error = drain(process.getErrorStream()); + var process = builder.start(); + var output = drain(process.getInputStream()); + var error = drain(process.getErrorStream()); if (!error.isEmpty()) { throw new IllegalArgumentException("Error for command '" + fullCmd + "':\n" + error); } - Matcher matcher = FIND_YEAR.matcher(output); + var matcher = FIND_YEAR.matcher(output); if (matcher.find()) { return matcher.group(1); } else { @@ -471,8 +470,8 @@ private static String parseYear(String cmd, File file) throws IOException { @SuppressFBWarnings("DM_DEFAULT_ENCODING") private static String drain(InputStream stream) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - byte[] buf = new byte[1024]; + var output = new ByteArrayOutputStream(); + var buf = new byte[1024]; int numRead; while ((numRead = stream.read(buf)) != -1) { output.write(buf, 0, numRead); diff --git a/lib/src/main/java/com/diffplug/spotless/generic/PipeStepPair.java b/lib/src/main/java/com/diffplug/spotless/generic/PipeStepPair.java index 38373fec59..547992c9f0 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/PipeStepPair.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/PipeStepPair.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. @@ -23,7 +23,6 @@ import java.util.Collection; import java.util.List; import java.util.Objects; -import java.util.regex.Matcher; import java.util.regex.Pattern; import com.diffplug.spotless.Formatter; @@ -91,8 +90,8 @@ public FormatterStep buildStepWhichAppliesSubSteps(Path rootPath, Collection state::format); out = FormatterStep.create(name + "Out", stateOut, state -> state::format); } @@ -128,7 +127,7 @@ Formatter buildFormatter(Path rootDir) { private String format(Formatter formatter, String unix, File file) throws Exception { groups.clear(); - Matcher matcher = regex.matcher(unix); + var matcher = regex.matcher(unix); while (matcher.find()) { // apply the formatter to each group groups.add(formatter.compute(matcher.group(1), file)); @@ -152,7 +151,7 @@ public StateIn(Pattern regex) { private String format(String unix) throws Exception { groups.clear(); - Matcher matcher = regex.matcher(unix); + var matcher = regex.matcher(unix); while (matcher.find()) { groups.add(matcher.group(1)); } @@ -182,9 +181,9 @@ private static String stateOutCompute(StateIn in, StringBuilder builder, String return unix; } builder.setLength(0); - Matcher matcher = in.regex.matcher(unix); - int lastEnd = 0; - int groupIdx = 0; + var matcher = in.regex.matcher(unix); + var lastEnd = 0; + var groupIdx = 0; while (matcher.find()) { builder.append(unix, lastEnd, matcher.start(1)); builder.append(in.groups.get(groupIdx)); @@ -196,7 +195,7 @@ private static String stateOutCompute(StateIn in, StringBuilder builder, String return builder.toString(); } else { // throw an error with either the full regex, or the nicer open/close pair - Matcher openClose = Pattern.compile("\\\\Q([\\s\\S]*?)\\\\E" + "\\Q([\\s\\S]*?)\\E" + "\\\\Q([\\s\\S]*?)\\\\E") + var openClose = Pattern.compile("\\\\Q([\\s\\S]*?)\\\\E" + "\\Q([\\s\\S]*?)\\E" + "\\\\Q([\\s\\S]*?)\\\\E") .matcher(in.regex.pattern()); String pattern; if (openClose.matches()) { 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..ccf1dabf11 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java @@ -21,7 +21,6 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import java.util.regex.Matcher; import java.util.regex.Pattern; import com.diffplug.spotless.FormatterFunc; @@ -443,11 +442,11 @@ FormatterFunc toFormatter() { */ String fixupTypeAnnotations(String unixStr) { // Each element of `lines` ends with a newline. - String[] lines = unixStr.split("((?<=\n))"); - for (int i = 0; i < lines.length - 1; i++) { - String line = lines[i]; + var lines = unixStr.split("((?<=\n))"); + for (var i = 0; i < lines.length - 1; i++) { + var line = lines[i]; if (endsWithTypeAnnotation(line)) { - String nextLine = lines[i + 1]; + var nextLine = lines[i + 1]; if (startsWithCommentPattern.matcher(nextLine).find()) { continue; } @@ -464,13 +463,13 @@ String fixupTypeAnnotations(String unixStr) { */ boolean endsWithTypeAnnotation(String unixLine) { // Remove trailing newline. - String line = unixLine.replaceAll("\\s+$", ""); - Matcher m = trailingAnnoPattern.matcher(line); + var line = unixLine.replaceAll("\\s+$", ""); + var m = trailingAnnoPattern.matcher(line); if (!m.find()) { return false; } - String preceding = line.substring(0, m.start()); - String basename = m.group(1); + var preceding = line.substring(0, m.start()); + var basename = m.group(1); if (withinCommentPattern.matcher(preceding).find()) { return false; diff --git a/lib/src/main/java/com/diffplug/spotless/java/ImportOrderStep.java b/lib/src/main/java/com/diffplug/spotless/java/ImportOrderStep.java index 686c9cfcaf..e1f4c77dba 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/ImportOrderStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/ImportOrderStep.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. @@ -94,9 +94,9 @@ private static List getImportOrder(File importsFile) { } private static Map.Entry splitIntoIndexAndName(String line) { - String[] pieces = line.split("="); - Integer index = Integer.valueOf(pieces[0]); - String name = pieces.length == 2 ? pieces[1] : ""; + var pieces = line.split("="); + var index = Integer.valueOf(pieces[0]); + var name = pieces.length == 2 ? pieces[1] : ""; return new SimpleImmutableEntry<>(index, name); } diff --git a/lib/src/main/java/com/diffplug/spotless/java/ImportSorter.java b/lib/src/main/java/com/diffplug/spotless/java/ImportSorter.java index edfc948487..c0d6ff2df5 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/ImportSorter.java +++ b/lib/src/main/java/com/diffplug/spotless/java/ImportSorter.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,15 +38,15 @@ final class ImportSorter { String format(String raw, String lineFormat) { // parse file - Scanner scanner = new Scanner(raw); - int firstImportLine = 0; - int lastImportLine = 0; - int line = 0; - boolean isMultiLineComment = false; + var scanner = new Scanner(raw); + var firstImportLine = 0; + var lastImportLine = 0; + var line = 0; + var isMultiLineComment = false; List imports = new ArrayList<>(); while (scanner.hasNext()) { line++; - String next = scanner.nextLine(); + var next = scanner.nextLine(); if (next == null) { break; } @@ -60,7 +60,7 @@ String format(String raw, String lineFormat) { } if (next.startsWith("import ")) { - int i = next.indexOf("."); + var i = next.indexOf("."); if (isNotValidImport(i)) { continue; } @@ -68,9 +68,9 @@ String format(String raw, String lineFormat) { firstImportLine = line; } lastImportLine = line; - int endIndex = next.indexOf(";"); + var endIndex = next.indexOf(";"); - String imprt = next.substring(START_INDEX_OF_IMPORTS_PACKAGE_DECLARATION, endIndex != -1 ? endIndex : next.length()); + var imprt = next.substring(START_INDEX_OF_IMPORTS_PACKAGE_DECLARATION, endIndex != -1 ? endIndex : next.length()); if (!isMultiLineComment && !imports.contains(imprt)) { imports.add(imprt); } @@ -86,7 +86,7 @@ String format(String raw, String lineFormat) { } private static boolean isBeginningOfScope(String line) { - int scope = line.indexOf("{"); + var scope = line.indexOf("{"); if (0 <= scope) { return !line.substring(0, scope).contains("//"); } @@ -97,13 +97,13 @@ private static String applyImportsToDocument(final String document, int firstImp if (document.isEmpty()) { return document; } - boolean importsAlreadyAppended = false; - Scanner scanner = new Scanner(document); - int curentLine = 0; - final StringBuilder sb = new StringBuilder(); + var importsAlreadyAppended = false; + var scanner = new Scanner(document); + var curentLine = 0; + final var sb = new StringBuilder(); while (scanner.hasNext()) { curentLine++; - String next = scanner.nextLine(); + var next = scanner.nextLine(); if (next == null) { break; } diff --git a/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java b/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java index 1f014ba95e..2e15df194a 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java +++ b/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java @@ -63,7 +63,7 @@ public List getSubGroups() { } static List sort(List imports, List importsOrder, boolean wildcardsLast, String lineFormat) { - ImportSorterImpl importsSorter = new ImportSorterImpl(importsOrder, wildcardsLast); + var importsSorter = new ImportSorterImpl(importsOrder, wildcardsLast); return importsSorter.sort(imports, lineFormat); } @@ -88,14 +88,14 @@ private ImportSorterImpl(List importOrder, boolean wildcardsLast) { } private void putStaticItemIfNotExists(List importsGroups) { - boolean catchAllSubGroupExist = importsGroups.stream().anyMatch(group -> group.getSubGroups().contains(STATIC_KEYWORD)); + var catchAllSubGroupExist = importsGroups.stream().anyMatch(group -> group.getSubGroups().contains(STATIC_KEYWORD)); if (catchAllSubGroupExist) { return; } - int indexOfFirstStatic = 0; - for (int i = 0; i < importsGroups.size(); i++) { - boolean subgroupMatch = importsGroups.get(i).getSubGroups().stream().anyMatch(subgroup -> subgroup.startsWith(STATIC_KEYWORD)); + var indexOfFirstStatic = 0; + for (var i = 0; i < importsGroups.size(); i++) { + var subgroupMatch = importsGroups.get(i).getSubGroups().stream().anyMatch(subgroup -> subgroup.startsWith(STATIC_KEYWORD)); if (subgroupMatch) { indexOfFirstStatic = i; } @@ -104,7 +104,7 @@ private void putStaticItemIfNotExists(List importsGroups) { } private void putCatchAllGroupIfNotExists(List importsGroups) { - boolean catchAllSubGroupExist = importsGroups.stream().anyMatch(group -> group.getSubGroups().contains(CATCH_ALL_SUBGROUP)); + var catchAllSubGroupExist = importsGroups.stream().anyMatch(group -> group.getSubGroups().contains(CATCH_ALL_SUBGROUP)); if (!catchAllSubGroupExist) { importsGroups.add(new ImportsGroup(CATCH_ALL_SUBGROUP)); } @@ -115,7 +115,7 @@ private void putCatchAllGroupIfNotExists(List importsGroups) { */ private void filterMatchingImports(List imports) { for (String anImport : imports) { - String orderItem = getBestMatchingImportOrderItem(anImport); + var orderItem = getBestMatchingImportOrderItem(anImport); if (orderItem != null) { matchingImports.computeIfAbsent(orderItem, key -> new ArrayList<>()); matchingImports.get(orderItem).add(anImport); @@ -148,7 +148,7 @@ private void mergeNotMatchingItems(boolean staticItems) { if (!matchesStatic(staticItems, notMatchingItem)) { continue; } - boolean isOrderItem = isOrderItem(notMatchingItem, staticItems); + var isOrderItem = isOrderItem(notMatchingItem, staticItems); if (!isOrderItem) { matchingImports.computeIfAbsent(CATCH_ALL_SUBGROUP, key -> new ArrayList<>()); matchingImports.get(CATCH_ALL_SUBGROUP).add(notMatchingItem); @@ -157,19 +157,19 @@ private void mergeNotMatchingItems(boolean staticItems) { } private boolean isOrderItem(String notMatchingItem, boolean staticItems) { - boolean contains = allImportOrderItems.contains(notMatchingItem); + var contains = allImportOrderItems.contains(notMatchingItem); return contains && matchesStatic(staticItems, notMatchingItem); } private static boolean matchesStatic(boolean staticItems, String notMatchingItem) { - boolean isStatic = notMatchingItem.startsWith(STATIC_KEYWORD); + var isStatic = notMatchingItem.startsWith(STATIC_KEYWORD); return (isStatic && staticItems) || (!isStatic && !staticItems); } private List mergeMatchingItems() { List template = new ArrayList<>(); for (ImportsGroup group : importsGroups) { - boolean groupIsNotEmpty = false; + var groupIsNotEmpty = false; for (String subgroup : group.getSubGroups()) { List strings = matchingImports.get(subgroup); if (strings == null || strings.isEmpty()) { @@ -212,16 +212,16 @@ private List getResult(List sortedImported, String lineFormat) { if (order1.equals(order2)) { throw new IllegalArgumentException("orders are same"); } - for (int i = 0; i < anImport.length() - 1; i++) { + for (var i = 0; i < anImport.length() - 1; i++) { if (order1.length() - 1 == i && order2.length() - 1 != i) { return order2; } if (order2.length() - 1 == i && order1.length() - 1 != i) { return order1; } - char orderChar1 = order1.length() != 0 ? order1.charAt(i) : ' '; - char orderChar2 = order2.length() != 0 ? order2.charAt(i) : ' '; - char importChar = anImport.charAt(i); + var orderChar1 = order1.length() != 0 ? order1.charAt(i) : ' '; + var orderChar2 = order2.length() != 0 ? order2.charAt(i) : ' '; + var importChar = anImport.charAt(i); if (importChar == orderChar1 && importChar != orderChar2) { return order1; @@ -244,15 +244,15 @@ private OrderingComparator(boolean wildcardsLast) { @Override public int compare(String string1, String string2) { - int string1WildcardIndex = string1.indexOf('*'); - int string2WildcardIndex = string2.indexOf('*'); - boolean string1IsWildcard = string1WildcardIndex >= 0; - boolean string2IsWildcard = string2WildcardIndex >= 0; + var string1WildcardIndex = string1.indexOf('*'); + var string2WildcardIndex = string2.indexOf('*'); + var string1IsWildcard = string1WildcardIndex >= 0; + var string2IsWildcard = string2WildcardIndex >= 0; if (string1IsWildcard == string2IsWildcard) { return string1.compareTo(string2); } - int prefixLength = string1IsWildcard ? string1WildcardIndex : string2WildcardIndex; - boolean samePrefix = string1.regionMatches(0, string2, 0, prefixLength); + var prefixLength = string1IsWildcard ? string1WildcardIndex : string2WildcardIndex; + var samePrefix = string1.regionMatches(0, string2, 0, prefixLength); if (!samePrefix) { return string1.compareTo(string2); } diff --git a/lib/src/main/java/com/diffplug/spotless/java/ModuleHelper.java b/lib/src/main/java/com/diffplug/spotless/java/ModuleHelper.java index e05a6a8b7f..902248ef07 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/ModuleHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/java/ModuleHelper.java @@ -15,7 +15,6 @@ */ package com.diffplug.spotless.java; -import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -65,7 +64,7 @@ public static synchronized void doOpenInternalPackagesIfRequired() { openPackages(unavailableRequiredPackages); final List failedToOpen = unavailableRequiredPackages(); if (!failedToOpen.isEmpty()) { - final StringBuilder message = new StringBuilder(); + final var message = new StringBuilder(); message.append("WARNING: Some required internal classes are unavailable. Please consider adding the following JVM arguments\n"); message.append("WARNING: "); for (String name : failedToOpen) { @@ -83,8 +82,8 @@ public static synchronized void doOpenInternalPackagesIfRequired() { private static List unavailableRequiredPackages() { final List packages = new ArrayList<>(); for (Map.Entry e : REQUIRED_PACKAGES_TO_TEST_CLASSES.entrySet()) { - final String key = e.getKey(); - final String value = e.getValue(); + final var key = e.getKey(); + final var value = e.getValue(); try { final Class clazz = Class.forName(key + "." + value); if (clazz.isEnum()) { @@ -110,12 +109,12 @@ private static void openPackages(Collection packagesToOpen) throws Throw final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe"); unsafeField.setAccessible(true); final Unsafe unsafe = (Unsafe) unsafeField.get(null); - final Field implLookupField = MethodHandles.Lookup.class.getDeclaredField("IMPL_LOOKUP"); - final MethodHandles.Lookup lookup = (MethodHandles.Lookup) unsafe.getObject( + final var implLookupField = MethodHandles.Lookup.class.getDeclaredField("IMPL_LOOKUP"); + final var lookup = (MethodHandles.Lookup) unsafe.getObject( unsafe.staticFieldBase(implLookupField), unsafe.staticFieldOffset(implLookupField)); - final MethodHandle modifiers = lookup.findSetter(Method.class, "modifiers", Integer.TYPE); - final Method exportMethod = Class.forName("java.lang.Module").getDeclaredMethod("implAddOpens", String.class); + final var modifiers = lookup.findSetter(Method.class, "modifiers", Integer.TYPE); + final var exportMethod = Class.forName("java.lang.Module").getDeclaredMethod("implAddOpens", String.class); modifiers.invokeExact(exportMethod, Modifier.PUBLIC); for (Object module : modules) { final Collection packages = (Collection) module.getClass().getMethod("getPackages").invoke(module); @@ -132,11 +131,11 @@ private static void openPackages(Collection packagesToOpen) throws Throw private static Collection allModules() { // calling ModuleLayer.boot().modules() by reflection try { - final Object boot = Class.forName("java.lang.ModuleLayer").getMethod("boot").invoke(null); + final var boot = Class.forName("java.lang.ModuleLayer").getMethod("boot").invoke(null); if (boot == null) { return null; } - final Object modules = boot.getClass().getMethod("modules").invoke(boot); + final var modules = boot.getClass().getMethod("modules").invoke(boot); return (Collection) modules; } catch (Exception ignore) { return null; diff --git a/lib/src/main/java/com/diffplug/spotless/kotlin/BadSemver.java b/lib/src/main/java/com/diffplug/spotless/kotlin/BadSemver.java index 771c27eb3e..6e942a72b0 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/BadSemver.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/BadSemver.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. @@ -15,18 +15,17 @@ */ package com.diffplug.spotless.kotlin; -import java.util.regex.Matcher; import java.util.regex.Pattern; class BadSemver { protected static int version(String input) { - Matcher matcher = BAD_SEMVER.matcher(input); + var matcher = BAD_SEMVER.matcher(input); if (!matcher.find() || matcher.start() != 0) { throw new IllegalArgumentException("Version must start with " + BAD_SEMVER.pattern()); } - String major = matcher.group(1); - String minor = matcher.group(2); - String patch = matcher.group(3); + var major = matcher.group(1); + var minor = matcher.group(2); + var patch = matcher.group(3); return version(Integer.parseInt(major), Integer.parseInt(minor), patch != null ? Integer.parseInt(patch) : 0); } diff --git a/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java b/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java index d6a20bc5b3..e2ca553694 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java @@ -21,7 +21,6 @@ import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import java.util.Objects; import javax.annotation.Nullable; @@ -232,13 +231,13 @@ private FormatterFunc getFormatterFuncFallback(Style style, ClassLoader classLoa return input -> { try { if (style == DEFAULT) { - Method formatterMethod = getFormatterClazz(classLoader).getMethod(FORMATTER_METHOD, String.class); + var formatterMethod = getFormatterClazz(classLoader).getMethod(FORMATTER_METHOD, String.class); return (String) formatterMethod.invoke(getFormatterClazz(classLoader), input); } else { - Method formatterMethod = getFormatterClazz(classLoader).getMethod(FORMATTER_METHOD, + var formatterMethod = getFormatterClazz(classLoader).getMethod(FORMATTER_METHOD, getFormattingOptionsClazz(classLoader), String.class); - Object formattingOptions = getCustomFormattingOptions(classLoader, style); + var formattingOptions = getCustomFormattingOptions(classLoader, style); return (String) formatterMethod.invoke(getFormatterClazz(classLoader), formattingOptions, input); } } catch (InvocationTargetException e) { @@ -261,7 +260,7 @@ private Object getCustomFormattingOptions(ClassLoader classLoader, Style style) if (style == Style.DEFAULT || style == Style.DROPBOX) { Class formattingOptionsCompanionClazz = classLoader.loadClass(pkg + ".ktfmt.FormattingOptions$Companion"); Object companion = formattingOptionsCompanionClazz.getConstructors()[0].newInstance((Object) null); - Method formattingOptionsMethod = formattingOptionsCompanionClazz.getDeclaredMethod("dropboxStyle"); + var formattingOptionsMethod = formattingOptionsCompanionClazz.getDeclaredMethod("dropboxStyle"); return formattingOptionsMethod.invoke(companion); } else { throw new IllegalStateException("Versions pre-0.19 can only use Default and Dropbox styles"); diff --git a/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java b/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java index 4477c640c7..93d5c589fa 100644 --- a/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java +++ b/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java @@ -18,7 +18,6 @@ import static com.diffplug.spotless.markdown.LibMarkdownPreconditions.requireKeysAndValuesNonNull; import java.io.Serializable; -import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -103,7 +102,7 @@ FormatterFunc createFormat() throws Exception { // instantiate the formatter and get its format method Class formatterClazz = classLoader.loadClass(FORMATTER_CLASS); Object formatter = formatterClazz.getConstructor(Map.class, Consumer.class).newInstance(properties, loggingStream); - Method method = formatterClazz.getMethod(FORMATTER_METHOD, String.class); + var method = formatterClazz.getMethod(FORMATTER_METHOD, String.class); return input -> (String) method.invoke(formatter, input); } } diff --git a/lib/src/main/java/com/diffplug/spotless/markdown/LibMarkdownPreconditions.java b/lib/src/main/java/com/diffplug/spotless/markdown/LibMarkdownPreconditions.java index 576535b1cb..ef4b491737 100644 --- a/lib/src/main/java/com/diffplug/spotless/markdown/LibMarkdownPreconditions.java +++ b/lib/src/main/java/com/diffplug/spotless/markdown/LibMarkdownPreconditions.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. @@ -25,7 +25,7 @@ private LibMarkdownPreconditions() {} static Map requireKeysAndValuesNonNull(Map map) { Objects.requireNonNull(map); map.forEach((key, value) -> { - String errorMessage = key + "=" + value; + var errorMessage = key + "=" + value; Objects.requireNonNull(key, errorMessage); Objects.requireNonNull(value, errorMessage); }); 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 a4480fe7fc..8815efad98 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java @@ -181,7 +181,7 @@ private void setConfigToCallOptions(Map eslintCallOptions) if (eslintConfig instanceof EslintTypescriptConfig) { // if we are a ts config, see if we need to use specific paths or use default projectDir File tsConfigFilePath = ((EslintTypescriptConfig) eslintConfig).getTypescriptConfigPath(); - File tsConfigRootDir = tsConfigFilePath != null ? tsConfigFilePath.getParentFile() : projectDir; + var tsConfigRootDir = tsConfigFilePath != null ? tsConfigFilePath.getParentFile() : projectDir; eslintCallOptions.put(FormatOption.TS_CONFIG_ROOT_DIR, nodeModulesDir.getAbsoluteFile().toPath().relativize(tsConfigRootDir.getAbsoluteFile().toPath()).toString()); } } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java b/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java index 76016d68db..e6fed1a00f 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2020 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. @@ -156,7 +156,7 @@ public CandidateOnPathListEnvironmentVar(String environmentVar, String fileName, @Override public Optional get() { - String pathList = System.getenv(environmentVar); + var pathList = System.getenv(environmentVar); if (pathList != null) { return Arrays.stream(pathList.split(System.getProperty("path.separator", ":"))) .map(File::new) diff --git a/lib/src/main/java/com/diffplug/spotless/npm/JsonEscaper.java b/lib/src/main/java/com/diffplug/spotless/npm/JsonEscaper.java index 163818d0e7..bf779da5cd 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/JsonEscaper.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/JsonEscaper.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-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. @@ -56,11 +56,11 @@ private static String jsonEscape(String unescaped) { * additionally we handle xhtml '' string * and non-ascii chars */ - StringBuilder escaped = new StringBuilder(); + var escaped = new StringBuilder(); escaped.append('"'); char b; char c = 0; - for (int i = 0; i < unescaped.length(); i++) { + for (var i = 0; i < unescaped.length(); i++) { b = c; c = unescaped.charAt(i); switch (c) { @@ -95,7 +95,7 @@ private static String jsonEscape(String unescaped) { if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { escaped.append('\\').append('u'); - String hexString = Integer.toHexString(c); + var hexString = Integer.toHexString(c); escaped.append("0000", 0, 4 - hexString.length()); escaped.append(hexString); } else { diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeExecutableResolver.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeExecutableResolver.java index eb30ae78b8..42cfda1781 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeExecutableResolver.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeExecutableResolver.java @@ -25,7 +25,7 @@ private NodeExecutableResolver() { } static String nodeExecutableName() { - String nodeName = "node"; + var nodeName = "node"; if (PlatformInfo.normalizedOS() == PlatformInfo.OS.WINDOWS) { nodeName += ".exe"; } @@ -36,7 +36,7 @@ static Optional tryFindNextTo(File npmExecutable) { if (npmExecutable == null) { return Optional.empty(); } - File nodeExecutable = new File(npmExecutable.getParentFile(), nodeExecutableName()); + var nodeExecutable = new File(npmExecutable.getParentFile(), nodeExecutableName()); if (nodeExecutable.exists() && nodeExecutable.isFile() && nodeExecutable.canExecute()) { return Optional.of(nodeExecutable); } 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 0086064194..03dd6167a2 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java @@ -80,7 +80,7 @@ public CachingNmpInstall(NpmProcess actualNpmInstallProcess, NodeServerLayout no @Override public Result waitFor() { - String entryName = entryName(); + var entryName = entryName(); if (shadowCopy.entryExists(entryName, NodeServerLayout.NODE_MODULES)) { timedLogger.withInfo("Using cached node_modules for {} from {}", entryName, cacheDir) .run(() -> shadowCopy.copyEntryInto(entryName(), NodeServerLayout.NODE_MODULES, nodeServerLayout.nodeModulesDir())); 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..d354b7443b 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java @@ -18,7 +18,6 @@ import java.io.File; import java.nio.file.Files; import java.nio.file.Path; -import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; @@ -47,11 +46,11 @@ class NodeServerLayout { private static String nodeModulesDirName(String packageJsonContent) { String md5Hash = NpmResourceHelper.md5(packageJsonContent); - Matcher matcher = PACKAGE_JSON_NAME_PATTERN.matcher(packageJsonContent); + var matcher = PACKAGE_JSON_NAME_PATTERN.matcher(packageJsonContent); if (!matcher.find()) { throw new IllegalArgumentException("package.json must contain a name property"); } - String packageName = matcher.group(1); + var packageName = matcher.group(1); return String.format("%s-node-modules-%s", packageName, md5Hash); } @@ -89,7 +88,7 @@ public boolean isLayoutPrepared() { } public boolean isNodeModulesPrepared() { - Path nodeModulesInstallDirPath = new File(nodeModulesDir(), NODE_MODULES).toPath(); + var nodeModulesInstallDirPath = new File(nodeModulesDir(), NODE_MODULES).toPath(); if (!Files.isDirectory(nodeModulesInstallDirPath)) { return false; } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java index 8c233abc8c..e69e5bfcdb 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ private NpmExecutableResolver() { } static String npmExecutableName() { - String npmName = "npm"; + var npmName = "npm"; if (PlatformInfo.normalizedOS() == WINDOWS) { npmName += ".cmd"; } 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 3f262c813c..7d9fe6dccd 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java @@ -97,7 +97,7 @@ protected ServerProcessInfo npmRunServer() throws ServerStartException, IOExcept try { // The npm process will output the randomly selected port of the http server process to 'server.port' file // so in order to be safe, remove such a file if it exists before starting. - final File serverPortFile = new File(this.nodeServerLayout.nodeModulesDir(), "server.port"); + final var serverPortFile = new File(this.nodeServerLayout.nodeModulesDir(), "server.port"); NpmResourceHelper.deleteFileIfExists(serverPortFile); // start the http server in node server = nodeServeApp.startNpmServeProcess(); @@ -126,7 +126,7 @@ protected ServerProcessInfo npmRunServer() throws ServerStartException, IOExcept } protected static String replaceDevDependencies(String template, Map devDependencies) { - StringBuilder builder = new StringBuilder(); + var builder = new StringBuilder(); Iterator> entryIter = devDependencies.entrySet().iterator(); while (entryIter.hasNext()) { Map.Entry entry = entryIter.next(); @@ -143,7 +143,7 @@ protected static String replaceDevDependencies(String template, Map replacements) { - String result = template; + var result = template; for (Entry entry : replacements.entrySet()) { result = result.replaceAll("\\Q${" + entry.getKey() + "}\\E", entry.getValue()); } @@ -174,7 +174,7 @@ public void close() throws Exception { serverPortFile.getParent(), serverPort); if (server.isAlive()) { - boolean ended = server.waitFor(5, TimeUnit.SECONDS); + var ended = server.waitFor(5, TimeUnit.SECONDS); if (!ended) { logger.info("Force-Closing npm server in directory <{}> and port <{}>", serverPortFile.getParent(), serverPort); server.destroyForcibly().waitFor(); diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmPathResolver.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmPathResolver.java index 4759d2f914..ec443c0b50 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmPathResolver.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmPathResolver.java @@ -53,7 +53,7 @@ public File resolveNpmExecutable() { return this.explicitNpmExecutable; } if (this.explicitNodeExecutable != null) { - File nodeExecutableCandidate = new File(this.explicitNodeExecutable.getParentFile(), NpmExecutableResolver.npmExecutableName()); + var nodeExecutableCandidate = new File(this.explicitNodeExecutable.getParentFile(), NpmExecutableResolver.npmExecutableName()); if (nodeExecutableCandidate.canExecute()) { return nodeExecutableCandidate; } @@ -74,13 +74,13 @@ public File resolveNodeExecutable() { if (this.explicitNodeExecutable != null) { return this.explicitNodeExecutable; } - File npmExecutable = resolveNpmExecutable(); + var npmExecutable = resolveNpmExecutable(); return NodeExecutableResolver.tryFindNextTo(npmExecutable) .orElseThrow(() -> new IllegalStateException("Can't automatically determine node executable and none was specifically supplied!\n\n" + NodeExecutableResolver.explainMessage())); } public String resolveNpmrcContent() { - File npmrcFile = Optional.ofNullable(this.explicitNpmrcFile) + var npmrcFile = Optional.ofNullable(this.explicitNpmrcFile) .orElseGet(() -> new NpmrcResolver(additionalNpmrcLocations).tryFind() .orElse(null)); if (npmrcFile != null) { 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..3bd8d0448d 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java @@ -18,7 +18,6 @@ import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.security.MessageDigest; @@ -40,7 +39,7 @@ static void writeUtf8StringToFile(File file, String stringToWrite) throws IOExce } static void writeUtf8StringToOutputStream(String stringToWrite, OutputStream outputStream) throws IOException { - final byte[] bytes = stringToWrite.getBytes(StandardCharsets.UTF_8); + final var bytes = stringToWrite.getBytes(StandardCharsets.UTF_8); outputStream.write(bytes); } @@ -59,7 +58,7 @@ static String readUtf8StringFromClasspath(Class clazz, String... resourceName } static String readUtf8StringFromClasspath(Class clazz, String resourceName) { - try (InputStream input = clazz.getResourceAsStream(resourceName)) { + try (var input = clazz.getResourceAsStream(resourceName)) { return readUtf8StringFromInputStream(input); } catch (IOException e) { throw ThrowingEx.asRuntime(e); @@ -76,8 +75,8 @@ static String readUtf8StringFromFile(File file) { static String readUtf8StringFromInputStream(InputStream input) { try { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; + var output = new ByteArrayOutputStream(); + var buffer = new byte[1024]; int numRead; while ((numRead = input.read(buffer)) != -1) { output.write(buffer, 0, numRead); @@ -97,7 +96,7 @@ static void assertDirectoryExists(File directory) throws IOException { } static void awaitReadableFile(File file, Duration maxWaitTime) throws TimeoutException { - final long startedAt = System.currentTimeMillis(); + final var startedAt = System.currentTimeMillis(); while (!file.exists() || !file.canRead()) { // wait for at most maxWaitTime if ((System.currentTimeMillis() - startedAt) > maxWaitTime.toMillis()) { @@ -108,7 +107,7 @@ static void awaitReadableFile(File file, Duration maxWaitTime) throws TimeoutExc } static void awaitFileDeleted(File file, Duration maxWaitTime) throws TimeoutException { - final long startedAt = System.currentTimeMillis(); + final var startedAt = System.currentTimeMillis(); while (file.exists()) { // wait for at most maxWaitTime if ((System.currentTimeMillis() - startedAt) > maxWaitTime.toMillis()) { @@ -126,7 +125,7 @@ static File copyFileToDirAtSubpath(File file, File targetDir, String relativePat Objects.requireNonNull(relativePath); try { // create file pointing to relativePath in targetDir - final Path relativeTargetFile = Paths.get(targetDir.getAbsolutePath(), relativePath); + final var relativeTargetFile = Paths.get(targetDir.getAbsolutePath(), relativePath); assertDirectoryExists(relativeTargetFile.getParent().toFile()); Files.copy(file.toPath(), relativeTargetFile, StandardCopyOption.REPLACE_EXISTING); @@ -143,9 +142,9 @@ static String md5(File file) { static String md5(String fileContent) { MessageDigest md = ThrowingEx.get(() -> MessageDigest.getInstance("MD5")); md.update(fileContent.getBytes(StandardCharsets.UTF_8)); - byte[] digest = md.digest(); + var digest = md.digest(); // convert byte array digest to hex string - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); for (byte b : digest) { sb.append(String.format("%02x", b & 0xff)); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/PlatformInfo.java b/lib/src/main/java/com/diffplug/spotless/npm/PlatformInfo.java index 3ae624d7c0..6d1887e92f 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PlatformInfo.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PlatformInfo.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. @@ -25,11 +25,11 @@ private PlatformInfo() { } static OS normalizedOS() { - final String osNameProperty = System.getProperty("os.name"); + final var osNameProperty = System.getProperty("os.name"); if (osNameProperty == null) { throw new RuntimeException("No info about OS available, cannot decide which implementation of j2v8 to use"); } - final String normalizedOsName = osNameProperty.toLowerCase(Locale.ROOT); + final var normalizedOsName = osNameProperty.toLowerCase(Locale.ROOT); if (normalizedOsName.contains("win")) { return OS.WINDOWS; } @@ -47,11 +47,11 @@ static String normalizedOSName() { } static String normalizedArchName() { - final String osArchProperty = System.getProperty("os.arch"); + final var osArchProperty = System.getProperty("os.arch"); if (osArchProperty == null) { throw new RuntimeException("No info about ARCH available, cannot decide which implementation of j2v8 to use"); } - final String normalizedOsArch = osArchProperty.toLowerCase(Locale.ROOT); + final var normalizedOsArch = osArchProperty.toLowerCase(Locale.ROOT); if (normalizedOsArch.contains("64")) { return "x86_64"; 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..8a67539682 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java @@ -119,7 +119,7 @@ public PrettierFilePathPassingFormatterFunc(String prettierConfigOptions, Pretti @Override public String applyWithFile(String unix, File file) throws Exception { - final String prettierConfigOptionsWithFilepath = assertFilepathInConfigOptions(file); + final var prettierConfigOptionsWithFilepath = assertFilepathInConfigOptions(file); try { return restService.format(unix, prettierConfigOptionsWithFilepath); } catch (SimpleRestClient.SimpleRestResponseException e) { @@ -140,9 +140,9 @@ private String assertFilepathInConfigOptions(File file) { return prettierConfigOptions; } // if it is not there, we add it at the beginning of the Options - final int startOfConfigOption = prettierConfigOptions.indexOf('{'); - final boolean hasAnyConfigOption = prettierConfigOptions.indexOf(':', startOfConfigOption + 1) != -1; - final String filePathOption = "\"filepath\":\"" + file.getName() + "\""; + final var startOfConfigOption = prettierConfigOptions.indexOf('{'); + final var hasAnyConfigOption = prettierConfigOptions.indexOf(':', startOfConfigOption + 1) != -1; + final var filePathOption = "\"filepath\":\"" + file.getName() + "\""; return "{" + filePathOption + (hasAnyConfigOption ? "," : "") + prettierConfigOptions.substring(startOfConfigOption + 1); } } 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..cff6c2fcd0 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java @@ -88,7 +88,7 @@ public PrettierMissingParserException(@Nonnull File file, Exception cause) { } private static String recommendPlugin(File file) { - String pluginName = guessPlugin(file); + var pluginName = guessPlugin(file); return "A good candidate for file '" + file + "' is '" + pluginName + "\n" + "See if you can find it on \n" + "or search on npmjs.com for a plugin matching that name: " 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 044b5d70ea..001320ba8a 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java @@ -70,7 +70,7 @@ public File getEntry(String key, String fileName) { } private void storeEntry(String key, File orig) { - File target = entry(key, orig.getName()); + var target = entry(key, orig.getName()); if (target.exists()) { logger.debug("Shadow copy entry already exists: {}", key); // delete directory "target" recursively @@ -106,7 +106,7 @@ private boolean reserveSubFolder(String key) { } public File copyEntryInto(String key, String origName, File targetParentFolder) { - File target = Paths.get(targetParentFolder.getAbsolutePath(), origName).toFile(); + var target = Paths.get(targetParentFolder.getAbsolutePath(), origName).toFile(); if (target.exists()) { logger.warn("Shadow copy destination already exists, deleting! {}: {}", key, target); ThrowingEx.run(() -> Files.walkFileTree(target.toPath(), new DeleteDirectoryRecursively())); diff --git a/lib/src/main/java/com/diffplug/spotless/npm/SimpleJsonWriter.java b/lib/src/main/java/com/diffplug/spotless/npm/SimpleJsonWriter.java index 846f7f1cf3..9c2470a0d2 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/SimpleJsonWriter.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/SimpleJsonWriter.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. @@ -33,7 +33,7 @@ public class SimpleJsonWriter { private final LinkedHashMap valueMap = new LinkedHashMap<>(); public static SimpleJsonWriter of(Map values) { - SimpleJsonWriter writer = new SimpleJsonWriter(); + var writer = new SimpleJsonWriter(); writer.putAll(values); return writer; } 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..222029763f 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. @@ -20,7 +20,6 @@ import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; @@ -52,27 +51,27 @@ String post(String endpoint) throws SimpleRestException { String postJson(String endpoint, @Nullable String rawJson) throws SimpleRestException { try { - URL url = new URL(this.baseUrl + endpoint); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); + var url = new URL(this.baseUrl + endpoint); + var con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(60 * 1000); // one minute con.setReadTimeout(2 * 60 * 1000); // two minutes - who knows how large those files can actually get con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.setDoOutput(true); if (rawJson != null) { - try (OutputStream out = con.getOutputStream()) { + try (var out = con.getOutputStream()) { NpmResourceHelper.writeUtf8StringToOutputStream(rawJson, out); out.flush(); } } - int status = con.getResponseCode(); + var status = con.getResponseCode(); if (status != 200) { throw new SimpleRestResponseException(status, readError(con), "Unexpected response status code at " + endpoint); } - String response = readResponse(con); + var response = readResponse(con); return response; } catch (IOException e) { throw new SimpleRestIOException(e); @@ -88,7 +87,7 @@ private String readResponse(HttpURLConnection con) throws IOException { } private String readInputStream(InputStream inputStream) throws IOException { - try (BufferedInputStream input = new BufferedInputStream(inputStream)) { + try (var input = new BufferedInputStream(inputStream)) { return NpmResourceHelper.readUtf8StringFromInputStream(input); } } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/TimedLogger.java b/lib/src/main/java/com/diffplug/spotless/npm/TimedLogger.java index 537234fcee..db09dc13b0 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/TimedLogger.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/TimedLogger.java @@ -124,18 +124,18 @@ private Object[] paramsForEnd() { } private String durationString() { - long duration = ticker.read() - startedAt; + var duration = ticker.read() - startedAt; if (duration < 1000) { return duration + "ms"; } else if (duration < 1000 * 60) { - long seconds = duration / 1000; - long millis = duration - seconds * 1000; + var seconds = duration / 1000; + var millis = duration - seconds * 1000; return seconds + "." + millis + "s"; } else { // output in the format 3m 4.321s - long minutes = duration / (1000 * 60); - long seconds = (duration - minutes * 1000 * 60) / 1000; - long millis = duration - minutes * 1000 * 60 - seconds * 1000; + var minutes = duration / (1000 * 60); + var seconds = (duration - minutes * 1000 * 60) / 1000; + var millis = duration - minutes * 1000 * 60 - seconds * 1000; return minutes + "m" + (seconds + millis > 0 ? " " + seconds + "." + millis + "s" : ""); } } @@ -191,19 +191,19 @@ public TimedExec(LogActiveMethod logActiveMethod, LogToLevelMethod logMethod, Ti } public void run(ThrowingEx.Runnable r) { - try (Timed ignore = timed()) { + try (var ignore = timed()) { ThrowingEx.run(r); } } public T call(ThrowingEx.Supplier s) { - try (Timed ignore = timed()) { + try (var ignore = timed()) { return ThrowingEx.get(s); } } public void runChecked(ThrowingEx.Runnable r) throws Exception { - try (Timed ignore = timed()) { + try (var ignore = timed()) { r.run(); } } 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 a83c3e202a..8c742a4982 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java @@ -106,7 +106,7 @@ public FormatterFunc createFormatterFunc() { private Map unifyOptions() { Map unified = new HashMap<>(); if (!this.inlineTsFmtSettings.isEmpty()) { - File targetFile = new File(this.buildDir, "inline-tsfmt.json"); + var targetFile = new File(this.buildDir, "inline-tsfmt.json"); SimpleJsonWriter.of(this.inlineTsFmtSettings).toJsonFile(targetFile); unified.put("tsfmt", true); unified.put("tsfmtFile", targetFile.getAbsolutePath()); diff --git a/lib/src/main/java/com/diffplug/spotless/python/BlackStep.java b/lib/src/main/java/com/diffplug/spotless/python/BlackStep.java index 9bce2241dd..ddc7d6067d 100644 --- a/lib/src/main/java/com/diffplug/spotless/python/BlackStep.java +++ b/lib/src/main/java/com/diffplug/spotless/python/BlackStep.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. @@ -60,7 +60,7 @@ public FormatterStep create() { } private State createState() throws IOException, InterruptedException { - String trackingIssue = "\n github issue to handle this better: https://github.com/diffplug/spotless/issues/674"; + var trackingIssue = "\n github issue to handle this better: https://github.com/diffplug/spotless/issues/674"; ForeignExe exeAbsPath = ForeignExe.nameAndVersion("black", version) .pathToExe(pathToExe) .versionRegex(Pattern.compile("(?:black, version|black,|version) (\\S*)")) diff --git a/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java b/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java index 264ca679db..39c819b6a3 100644 --- a/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java +++ b/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java @@ -49,7 +49,7 @@ public static FormatterStep create(String version, Provisioner provisioner, @Nul } public static FormatterStep create(String version, @Nullable String scalaMajorVersion, Provisioner provisioner, @Nullable File configFile) { - String finalScalaMajorVersion = scalaMajorVersion == null ? DEFAULT_SCALA_MAJOR_VERSION : scalaMajorVersion; + var finalScalaMajorVersion = scalaMajorVersion == null ? DEFAULT_SCALA_MAJOR_VERSION : scalaMajorVersion; return FormatterStep.createLazy(NAME, () -> new State(JarState.from(MAVEN_COORDINATE + finalScalaMajorVersion + ":" + version, provisioner), configFile), 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..b68fdef4d9 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. @@ -59,15 +59,15 @@ public DBeaverSQLFormatterConfiguration(Properties properties) { this.keywordCase = KeywordCase.valueOf(properties.getProperty(SQL_FORMATTER_KEYWORD_CASE, "UPPER")); this.statementDelimiters = properties.getProperty(SQL_FORMATTER_STATEMENT_DELIMITER, SQLDialect.INSTANCE .getScriptDelimiter()); - String indentType = properties.getProperty(SQL_FORMATTER_INDENT_TYPE, "space"); - int indentSize = Integer.parseInt(properties.getProperty(SQL_FORMATTER_INDENT_SIZE, "4")); + var indentType = properties.getProperty(SQL_FORMATTER_INDENT_TYPE, "space"); + var indentSize = Integer.parseInt(properties.getProperty(SQL_FORMATTER_INDENT_SIZE, "4")); indentString = getIndentString(indentType, indentSize); } private String getIndentString(String indentType, int indentSize) { - char indentChar = indentType.equals("space") ? ' ' : '\t'; - StringBuilder stringBuilder = new StringBuilder(); - for (int i = 0; i < indentSize; i++) { + var indentChar = indentType.equals("space") ? ' ' : '\t'; + var stringBuilder = new StringBuilder(); + for (var i = 0; i < indentSize; i++) { stringBuilder.append(indentChar); } return stringBuilder.toString(); 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..fb9da6e65d 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,7 +64,7 @@ public int getPos() { } public String toString() { - final StringBuilder buf = new StringBuilder(); + final var buf = new StringBuilder(); buf.append(getClass().getName()); buf.append("type=").append(fType); buf.append(",string=").append(fString); 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..3ecc6296d1 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. @@ -53,7 +53,7 @@ public String format(final String argSql) { functionBracket.clear(); - boolean isSqlEndsWithNewLine = false; + var isSqlEndsWithNewLine = false; if (argSql.endsWith("\n")) { isSqlEndsWithNewLine = true; } @@ -61,7 +61,7 @@ public String format(final String argSql) { List list = fParser.parse(argSql); list = format(list); - StringBuilder after = new StringBuilder(argSql.length() + 20); + var after = new StringBuilder(argSql.length() + 20); for (FormatterToken token : list) { after.append(token.getString()); } @@ -115,7 +115,7 @@ private List format(final List argList) { } } - for (int index = 0; index < argList.size() - 2; index++) { + for (var index = 0; index < argList.size() - 2; index++) { FormatterToken t0 = argList.get(index); FormatterToken t1 = argList.get(index + 1); FormatterToken t2 = argList.get(index + 2); @@ -147,11 +147,11 @@ private List format(final List argList) { } } - int indent = 0; + var indent = 0; final List bracketIndent = new ArrayList<>(); FormatterToken prev = new FormatterToken(TokenType.SPACE, " "); - boolean encounterBetween = false; - for (int index = 0; index < argList.size(); index++) { + var encounterBetween = false; + for (var index = 0; index < argList.size(); index++) { token = argList.get(index); String tokenString = token.getString().toUpperCase(Locale.ENGLISH); if (token.getType() == TokenType.SYMBOL) { @@ -250,7 +250,7 @@ private List format(final List argList) { break; } } else if (token.getType() == TokenType.COMMENT) { - boolean isComment = false; + var isComment = false; String[] slComments = sqlDialect.getSingleLineComments(); for (String slc : slComments) { if (token.getString().startsWith(slc)) { @@ -304,7 +304,7 @@ private List format(final List argList) { } } - for (int index = 1; index < argList.size(); index++) { + for (var index = 1; index < argList.size(); index++) { prev = argList.get(index - 1); token = argList.get(index); @@ -355,7 +355,7 @@ private boolean isJoinStart(List argList, int index) { return false; } // check previous token - for (int i = index - 1; i >= 0; i--) { + for (var i = index - 1; i >= 0; i--) { FormatterToken token = argList.get(i); if (token.getType() == TokenType.SPACE) { continue; @@ -368,7 +368,7 @@ private boolean isJoinStart(List argList, int index) { } } // check last token - for (int i = index; i < argList.size(); i++) { + for (var i = index; i < argList.size(); i++) { FormatterToken token = argList.get(i); if (token.getType() == TokenType.SPACE) { continue; @@ -396,9 +396,9 @@ private int insertReturnAndIndent(final List argList, final int if (functionBracket.contains(Boolean.TRUE)) return 0; try { - final String defaultLineSeparator = getDefaultLineSeparator(); - StringBuilder s = new StringBuilder(defaultLineSeparator); - for (int index = 0; index < argIndent; index++) { + final var defaultLineSeparator = getDefaultLineSeparator(); + var s = new StringBuilder(defaultLineSeparator); + for (var index = 0; index < argIndent; index++) { s.append(formatterCfg.getIndentString()); } if (argIndex > 0) { @@ -411,7 +411,7 @@ private int insertReturnAndIndent(final List argList, final int s.setLength(1); final String comment = token.getString(); - final String withoutTrailingWhitespace = comment.replaceFirst("\\s*$", ""); + final var withoutTrailingWhitespace = comment.replaceFirst("\\s*$", ""); token.setString(withoutTrailingWhitespace); } } @@ -433,7 +433,7 @@ private int insertReturnAndIndent(final List argList, final int if (isDelimiter) { if (argList.size() > argIndex + 1) { - String string = s.toString(); + var string = s.toString(); argList.add(argIndex + 1, new FormatterToken(TokenType.SPACE, string + string)); } } else { 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..ac554b0780 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. @@ -49,7 +49,7 @@ class SQLTokensParser { this.quoteStrings = sqlDialect.getIdentifierQuoteStrings(); this.singleLineComments = sqlDialect.getSingleLineComments(); this.singleLineCommentStart = new char[this.singleLineComments.length]; - for (int i = 0; i < singleLineComments.length; i++) { + for (var i = 0; i < singleLineComments.length; i++) { if (singleLineComments[i].isEmpty()) singleLineCommentStart[i] = 0; else @@ -102,16 +102,16 @@ private static boolean isSymbol(final char argChar) { } private FormatterToken nextToken() { - int start_pos = fPos; + var start_pos = fPos; if (fPos >= fBefore.length()) { fPos++; return new FormatterToken(TokenType.END, "", start_pos); } - char fChar = fBefore.charAt(fPos); + var fChar = fBefore.charAt(fPos); if (isSpace(fChar)) { - StringBuilder workString = new StringBuilder(); + var workString = new StringBuilder(); for (;;) { workString.append(fChar); fChar = fBefore.charAt(fPos); @@ -127,7 +127,7 @@ private FormatterToken nextToken() { fPos++; return new FormatterToken(TokenType.SYMBOL, ";", start_pos); } else if (isDigit(fChar)) { - StringBuilder s = new StringBuilder(); + var s = new StringBuilder(); while (isDigit(fChar) || fChar == '.' || fChar == 'e' || fChar == 'E') { // if (ch == '.') type = Token.REAL; s.append(fChar); @@ -164,7 +164,7 @@ else if (contains(singleLineCommentStart, fChar)) { commentString = fBefore.substring(start_pos, fPos); return new FormatterToken(TokenType.COMMENT, commentString, start_pos); } else if (isLetter(fChar)) { - StringBuilder s = new StringBuilder(); + var s = new StringBuilder(); while (isLetter(fChar) || isDigit(fChar) || fChar == '*' || structSeparator == fChar || catalogSeparator.indexOf(fChar) != -1) { s.append(fChar); fPos++; @@ -174,7 +174,7 @@ else if (contains(singleLineCommentStart, fChar)) { fChar = fBefore.charAt(fPos); } - String word = s.toString(); + var word = s.toString(); if (commands.contains(word.toUpperCase(Locale.ENGLISH))) { s.setLength(0); for (; fPos < fBefore.length(); fPos++) { @@ -193,12 +193,12 @@ else if (contains(singleLineCommentStart, fChar)) { return new FormatterToken(TokenType.NAME, word, start_pos); } else if (fChar == '/') { fPos++; - char ch2 = fBefore.charAt(fPos); + var ch2 = fBefore.charAt(fPos); if (ch2 != '*') { return new FormatterToken(TokenType.SYMBOL, "/", start_pos); } - StringBuilder s = new StringBuilder("/*"); + var s = new StringBuilder("/*"); fPos++; for (;;) { int ch0 = fChar; @@ -212,7 +212,7 @@ else if (contains(singleLineCommentStart, fChar)) { } else { if (fChar == '\'' || isQuoteChar(fChar)) { fPos++; - char endQuoteChar = fChar; + var endQuoteChar = fChar; // Close quote char may differ if (quoteStrings != null) { for (String[] quoteString : quoteStrings) { @@ -223,13 +223,13 @@ else if (contains(singleLineCommentStart, fChar)) { } } - StringBuilder s = new StringBuilder(); + var s = new StringBuilder(); s.append(fChar); for (;;) { fChar = fBefore.charAt(fPos); s.append(fChar); fPos++; - char fNextChar = fPos >= fBefore.length() - 1 ? 0 : fBefore.charAt(fPos); + var fNextChar = fPos >= fBefore.length() - 1 ? 0 : fBefore.charAt(fPos); if (fChar == endQuoteChar && fNextChar == endQuoteChar) { // Escaped quote s.append(fChar); @@ -243,12 +243,12 @@ else if (contains(singleLineCommentStart, fChar)) { } else if (isSymbol(fChar)) { - StringBuilder s = new StringBuilder(String.valueOf(fChar)); + var s = new StringBuilder(String.valueOf(fChar)); fPos++; if (fPos >= fBefore.length()) { return new FormatterToken(TokenType.SYMBOL, s.toString(), start_pos); } - char ch2 = fBefore.charAt(fPos); + var ch2 = fBefore.charAt(fPos); for (String aTwoCharacterSymbol : twoCharacterSymbol) { if (aTwoCharacterSymbol.charAt(0) == fChar && aTwoCharacterSymbol.charAt(1) == ch2) { fPos++; diff --git a/lib/src/palantirJavaFormat/java/com/diffplug/spotless/glue/pjf/PalantirJavaFormatFormatterFunc.java b/lib/src/palantirJavaFormat/java/com/diffplug/spotless/glue/pjf/PalantirJavaFormatFormatterFunc.java index 6824cdbc48..dd29f538a6 100644 --- a/lib/src/palantirJavaFormat/java/com/diffplug/spotless/glue/pjf/PalantirJavaFormatFormatterFunc.java +++ b/lib/src/palantirJavaFormat/java/com/diffplug/spotless/glue/pjf/PalantirJavaFormatFormatterFunc.java @@ -1,5 +1,5 @@ /* - * Copyright 2022 DiffPlug + * Copyright 2022-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ public PalantirJavaFormatFormatterFunc() { @Override public String apply(String input) throws Exception { - String source = input; + var source = input; source = ImportOrderer.reorderImports(source, JavaFormatterOptions.Style.PALANTIR); source = RemoveUnusedImports.removeUnusedImports(source); return formatter.formatSource(source); diff --git a/lib/src/scalafmt/java/com/diffplug/spotless/glue/scalafmt/ScalafmtFormatterFunc.java b/lib/src/scalafmt/java/com/diffplug/spotless/glue/scalafmt/ScalafmtFormatterFunc.java index 49e1b6a1be..3a117fcdd2 100644 --- a/lib/src/scalafmt/java/com/diffplug/spotless/glue/scalafmt/ScalafmtFormatterFunc.java +++ b/lib/src/scalafmt/java/com/diffplug/spotless/glue/scalafmt/ScalafmtFormatterFunc.java @@ -1,5 +1,5 @@ /* - * Copyright 2022 DiffPlug + * Copyright 2022-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,7 +42,7 @@ public ScalafmtFormatterFunc(FileSignature configSignature) throws Exception { config = (ScalafmtConfig) method.invoke(ScalafmtConfig$.MODULE$); } else { File file = configSignature.getOnlyFile(); - String configStr = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + var configStr = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); config = Scalafmt.parseHoconConfig(configStr).get(); } } diff --git a/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java b/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java index 22a0249634..9bad3de65d 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 @@ -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. @@ -41,7 +41,7 @@ public SortPomFormatterFunc(SortPomCfg cfg) { @Override public String apply(String input) throws Exception { // SortPom expects a file to sort, so we write the inpout into a temporary file - File pom = File.createTempFile("pom", ".xml"); + var pom = File.createTempFile("pom", ".xml"); pom.deleteOnExit(); IOUtils.write(input, new FileOutputStream(pom), cfg.encoding); SortPomImpl sortPom = new SortPomImpl(); diff --git a/lib/src/test/java/com/diffplug/spotless/RingBufferByteArrayOutputStreamTest.java b/lib/src/test/java/com/diffplug/spotless/RingBufferByteArrayOutputStreamTest.java index 94fa49dbc1..e4bb2bce7c 100644 --- a/lib/src/test/java/com/diffplug/spotless/RingBufferByteArrayOutputStreamTest.java +++ b/lib/src/test/java/com/diffplug/spotless/RingBufferByteArrayOutputStreamTest.java @@ -84,7 +84,7 @@ void toByteArrayBehavesOverwritingAtExactlyLimit(String name, ByteWriteStrategy void writeToBehavesNormallyWithinLimit(String name, ByteWriteStrategy writeStrategy) throws IOException { RingBufferByteArrayOutputStream stream = new RingBufferByteArrayOutputStream(12, 1); writeStrategy.write(stream, bytes); - ByteArrayOutputStream target = new ByteArrayOutputStream(); + var target = new ByteArrayOutputStream(); stream.writeTo(target); Assertions.assertThat(target.toByteArray()).isEqualTo(bytes); } @@ -94,7 +94,7 @@ void writeToBehavesNormallyWithinLimit(String name, ByteWriteStrategy writeStrat void writeToBehavesOverwritingOverLimit(String name, ByteWriteStrategy writeStrategy) throws IOException { RingBufferByteArrayOutputStream stream = new RingBufferByteArrayOutputStream(4, 1); writeStrategy.write(stream, bytes); - ByteArrayOutputStream target = new ByteArrayOutputStream(); + var target = new ByteArrayOutputStream(); stream.writeTo(target); Assertions.assertThat(target.toByteArray()).hasSize(4); Assertions.assertThat(target.toByteArray()).isEqualTo(new byte[]{'6', '7', '8', '9'}); @@ -105,7 +105,7 @@ void writeToBehavesOverwritingOverLimit(String name, ByteWriteStrategy writeStra void writeToBehavesNormallyAtExactlyLimit(String name, ByteWriteStrategy writeStrategy) throws IOException { RingBufferByteArrayOutputStream stream = new RingBufferByteArrayOutputStream(bytes.length, 1); writeStrategy.write(stream, bytes); - ByteArrayOutputStream target = new ByteArrayOutputStream(); + var target = new ByteArrayOutputStream(); stream.writeTo(target); Assertions.assertThat(target.toByteArray()).isEqualTo(bytes); } @@ -143,7 +143,7 @@ private static ByteWriteStrategy oneByteAtATime() { private static ByteWriteStrategy twoBytesAtATime() { return (stream, bytes) -> { - for (int i = 0; i < bytes.length; i += 2) { + for (var i = 0; i < bytes.length; i += 2) { stream.write(bytes, i, 2); } }; @@ -151,8 +151,8 @@ private static ByteWriteStrategy twoBytesAtATime() { private static ByteWriteStrategy oneAndThenTwoBytesAtATime() { return (stream, bytes) -> { - int written = 0; - for (int i = 0; i + 3 < bytes.length; i += 3) { + var written = 0; + for (var i = 0; i + 3 < bytes.length; i += 3) { stream.write(bytes, i, 1); stream.write(bytes, i + 1, 2); written += 3; diff --git a/lib/src/test/java/com/diffplug/spotless/npm/TimedLoggerTest.java b/lib/src/test/java/com/diffplug/spotless/npm/TimedLoggerTest.java index f08d4f1622..87dd60e17a 100644 --- a/lib/src/test/java/com/diffplug/spotless/npm/TimedLoggerTest.java +++ b/lib/src/test/java/com/diffplug/spotless/npm/TimedLoggerTest.java @@ -208,7 +208,7 @@ public void assertHasEventWithMessageAndArguments(String message, Object... argu if (event.arguments().length != arguments.length) { return false; } - for (int i = 0; i < arguments.length; i++) { + for (var i = 0; i < arguments.length; i++) { if (!String.valueOf(event.arguments()[i]).equals(arguments[i])) { return false; } diff --git a/lib/src/testCompatKtLint0Dot48Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot48Dot0AdapterTest.java b/lib/src/testCompatKtLint0Dot48Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot48Dot0AdapterTest.java index c811b51233..50e57645e9 100644 --- a/lib/src/testCompatKtLint0Dot48Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot48Dot0AdapterTest.java +++ b/lib/src/testCompatKtLint0Dot48Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot48Dot0AdapterTest.java @@ -18,7 +18,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; -import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -33,8 +32,8 @@ public class KtLintCompat0Dot48Dot0AdapterTest { @Test public void testDefaults(@TempDir Path path) throws IOException { KtLintCompat0Dot48Dot0Adapter ktLintCompat0Dot48Dot0Adapter = new KtLintCompat0Dot48Dot0Adapter(); - String text = loadAndWriteText(path, "empty_class_body.kt"); - final Path filePath = Paths.get(path.toString(), "empty_class_body.kt"); + var text = loadAndWriteText(path, "empty_class_body.kt"); + final var filePath = Paths.get(path.toString(), "empty_class_body.kt"); Map userData = new HashMap<>(); @@ -47,8 +46,8 @@ public void testDefaults(@TempDir Path path) throws IOException { @Test public void testEditorConfigCanDisable(@TempDir Path path) throws IOException { KtLintCompat0Dot48Dot0Adapter ktLintCompat0Dot48Dot0Adapter = new KtLintCompat0Dot48Dot0Adapter(); - String text = loadAndWriteText(path, "fails_no_semicolons.kt"); - final Path filePath = Paths.get(path.toString(), "fails_no_semicolons.kt"); + var text = loadAndWriteText(path, "fails_no_semicolons.kt"); + final var filePath = Paths.get(path.toString(), "fails_no_semicolons.kt"); Map userData = new HashMap<>(); @@ -63,7 +62,7 @@ public void testEditorConfigCanDisable(@TempDir Path path) throws IOException { } private static String loadAndWriteText(Path path, String name) throws IOException { - try (InputStream is = KtLintCompat0Dot48Dot0AdapterTest.class.getResourceAsStream("/" + name)) { + try (var is = KtLintCompat0Dot48Dot0AdapterTest.class.getResourceAsStream("/" + name)) { Files.copy(is, path.resolve(name)); } return new String(Files.readAllBytes(path.resolve(name)), StandardCharsets.UTF_8); 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..5fffeca9e8 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 @@ -235,7 +235,7 @@ private final FileCollection parseTargetIsExclude(Object target, boolean isExclu } else if (target instanceof String) { File dir = getProject().getProjectDir(); ConfigurableFileTree matchedFiles = getProject().fileTree(dir); - String targetString = (String) target; + var targetString = (String) target; matchedFiles.include(targetString); // since people are likely to do '**/*.md', we want to make sure to exclude folders @@ -267,7 +267,7 @@ private final FileCollection parseTargetIsExclude(Object target, boolean isExclu } private static void relativizeIfSubdir(List relativePaths, File root, File dest) { - String relativized = relativize(root, dest); + var relativized = relativize(root, dest); if (relativized != null) { relativePaths.add(relativized); } @@ -278,8 +278,8 @@ private static void relativizeIfSubdir(List relativePaths, File root, Fi * or null if dest is not a child of root. */ static @Nullable String relativize(File root, File dest) { - String rootPath = root.getAbsolutePath(); - String destPath = dest.getAbsolutePath(); + var rootPath = root.getAbsolutePath(); + var destPath = dest.getAbsolutePath(); if (!destPath.startsWith(rootPath)) { return null; } else { @@ -302,7 +302,7 @@ public void addStep(FormatterStep newStep) { /** Returns the index of the existing step with the given name, or -1 if no such step exists. */ protected int getExistingStepIdx(String stepName) { - for (int i = 0; i < steps.size(); ++i) { + for (var i = 0; i < steps.size(); ++i) { if (steps.get(i).getName().equals(stepName)) { return i; } @@ -425,7 +425,7 @@ public class LicenseHeaderConfig { public LicenseHeaderConfig named(String name) { String existingStepName = builder.getName(); builder = builder.withName(name); - int existingStepIdx = getExistingStepIdx(existingStepName); + var existingStepIdx = getExistingStepIdx(existingStepName); if (existingStepIdx != -1) { steps.set(existingStepIdx, createStep()); } else { @@ -486,7 +486,7 @@ FormatterStep createStep() { if ("true".equals(spotless.project.findProperty(LicenseHeaderStep.FLAG_SET_LICENSE_HEADER_YEARS_FROM_GIT_HISTORY()))) { return YearMode.SET_FROM_GIT; } else { - boolean updateYear = updateYearWithLatest == null ? getRatchetFrom() != null : updateYearWithLatest; + var updateYear = updateYearWithLatest == null ? getRatchetFrom() != null : updateYearWithLatest; return updateYear ? YearMode.UPDATE_TO_TODAY : YearMode.PRESERVE; } }).build(); @@ -500,7 +500,7 @@ FormatterStep createStep() { * Spotless will look for a line that starts with this regular expression pattern to know what the "top" is. */ public LicenseHeaderConfig licenseHeader(String licenseHeader, String delimiter) { - LicenseHeaderConfig config = new LicenseHeaderConfig(LicenseHeaderStep.headerDelimiter(licenseHeader, delimiter)); + var config = new LicenseHeaderConfig(LicenseHeaderStep.headerDelimiter(licenseHeader, delimiter)); addStep(config.createStep()); return config; } @@ -512,9 +512,9 @@ public LicenseHeaderConfig licenseHeader(String licenseHeader, String delimiter) * Spotless will look for a line that starts with this regular expression pattern to know what the "top" is. */ public LicenseHeaderConfig licenseHeaderFile(Object licenseHeaderFile, String delimiter) { - LicenseHeaderConfig config = new LicenseHeaderConfig(LicenseHeaderStep.headerDelimiter(() -> { + var config = new LicenseHeaderConfig(LicenseHeaderStep.headerDelimiter(() -> { File file = getProject().file(licenseHeaderFile); - byte[] data = Files.readAllBytes(file.toPath()); + var data = Files.readAllBytes(file.toPath()); return new String(data, getEncoding()); }, delimiter)); addStep(config.createStep()); @@ -661,7 +661,7 @@ public PrettierConfig prettier(String version) { /** Uses exactly the npm packages specified in the map. */ public PrettierConfig prettier(Map devDependencies) { - PrettierConfig prettierConfig = new PrettierConfig(devDependencies); + var prettierConfig = new PrettierConfig(devDependencies); addStep(prettierConfig.createStep()); return prettierConfig; } 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..cfb27e2c94 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 @@ -65,7 +65,7 @@ static class DedupingProvisioner implements Provisioner { @Override public Set provisionWithTransitives(boolean withTransitives, Collection mavenCoordinates) { - Request req = new Request(withTransitives, mavenCoordinates); + var req = new Request(withTransitives, mavenCoordinates); Set result; synchronized (cache) { result = cache.get(req); @@ -86,7 +86,7 @@ public Set provisionWithTransitives(boolean withTransitives, Collection { - Request req = new Request(withTransitives, mavenCoordinates); + var req = new Request(withTransitives, mavenCoordinates); Set result; synchronized (cache) { result = cache.get(req); @@ -159,7 +159,7 @@ public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof Request) { - Request o = (Request) obj; + var o = (Request) obj; return o.withTransitives == withTransitives && o.mavenCoords.equals(mavenCoords); } else { return false; @@ -169,7 +169,7 @@ public boolean equals(Object obj) { @Override public String toString() { String coords = mavenCoords.toString(); - StringBuilder builder = new StringBuilder(); + var builder = new StringBuilder(); builder.append(coords, 1, coords.length() - 1); // strip off [] if (withTransitives) { builder.append(" with transitives"); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/IdeHook.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/IdeHook.java index 8d24e2230e..bec11980c3 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/IdeHook.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/IdeHook.java @@ -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. @@ -34,8 +34,8 @@ private static void dumpIsClean() { } static void performHook(SpotlessTaskImpl spotlessTask) { - String path = (String) spotlessTask.getProject().property(PROPERTY); - File file = new File(path); + var path = (String) spotlessTask.getProject().property(PROPERTY); + var file = new File(path); if (!file.isAbsolute()) { System.err.println("Argument passed to " + PROPERTY + " must be an absolute path"); return; 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..b8305c9f80 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 @@ -53,7 +53,7 @@ public JavascriptEslintConfig eslint(String version) { } public JavascriptEslintConfig eslint(Map devDependencies) { - JavascriptEslintConfig eslint = new JavascriptEslintConfig(devDependencies); + var eslint = new JavascriptEslintConfig(devDependencies); addStep(eslint.createStep()); return eslint; } 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..9a02843b5b 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. @@ -63,7 +63,7 @@ public void set(T value) { @Override public T get() { - Object value = daemonState.get(internalKey); + var value = daemonState.get(internalKey); if (value == null) { // TODO: throw TriggerConfigurationException(); (see https://github.com/diffplug/spotless/issues/987) throw cacheIsStale(); @@ -92,7 +92,7 @@ public boolean equals(Object o) { return true; if (o == null || getClass() != o.getClass()) return false; - InternalCacheKey that = (InternalCacheKey) o; + var that = (InternalCacheKey) o; return projectDir.equals(that.projectDir) && taskPath.equals(that.taskPath) && propertyName.equals(that.propertyName); } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SerializableMisc.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SerializableMisc.java index c4ffbc4837..01e71933a5 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SerializableMisc.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SerializableMisc.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. @@ -48,7 +48,7 @@ static T fromFile(Class clazz, File file) { } static void toStream(Serializable obj, OutputStream stream) { - try (ObjectOutputStream objectOutput = new ObjectOutputStream(stream)) { + try (var objectOutput = new ObjectOutputStream(stream)) { objectOutput.writeObject(obj); } catch (IOException e) { throw Errors.asRuntime(e); @@ -57,8 +57,8 @@ static void toStream(Serializable obj, OutputStream stream) { @SuppressWarnings("unchecked") static T fromStream(Class clazz, InputStream stream) { - try (ObjectInputStream objectInput = new ObjectInputStream(stream)) { - T object = (T) objectInput.readObject(); + try (var objectInput = new ObjectInputStream(stream)) { + var object = (T) objectInput.readObject(); Preconditions.checkArgument(clazz.isInstance(object), "Requires class %s, was %s", clazz, object); return object; } catch (ClassNotFoundException | IOException e) { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessDiagnoseTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessDiagnoseTask.java index f20957e650..82e3a7dbb9 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessDiagnoseTask.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessDiagnoseTask.java @@ -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. @@ -53,9 +53,9 @@ public void performAction() throws IOException { getLogger().debug(" well-behaved."); } else { // the file is misbehaved, so we'll write all its steps to DIAGNOSE_DIR - Path relative = srcRoot.relativize(file.toPath()); - Path diagnoseFile = diagnoseRoot.resolve(relative); - for (int i = 0; i < padded.steps().size(); ++i) { + var relative = srcRoot.relativize(file.toPath()); + var diagnoseFile = diagnoseRoot.resolve(relative); + for (var i = 0; i < padded.steps().size(); ++i) { Path path = Paths.get(diagnoseFile + "." + padded.type().name().toLowerCase(Locale.ROOT) + i); Files.createDirectories(path.getParent()); String version = padded.steps().get(i); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtension.java index 0a31a15764..7dfd268784 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtension.java @@ -239,7 +239,7 @@ protected final T maybeCreate(String name, Class return (T) existing; } } else { - T formatExtension = instantiateFormatExtension(clazz); + var formatExtension = instantiateFormatExtension(clazz); formats.put(name, formatExtension); createFormatTasks(name, formatExtension); return formatExtension; 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..db2cccbfd6 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. @@ -15,7 +15,6 @@ */ package com.diffplug.gradle.spotless; -import java.util.regex.Matcher; import java.util.regex.Pattern; import org.gradle.api.GradleException; @@ -28,12 +27,12 @@ public class SpotlessPluginRedirect implements Plugin { private static final Pattern BAD_SEMVER = Pattern.compile("(\\d+)\\.(\\d+)"); private static int badSemver(String input) { - Matcher matcher = BAD_SEMVER.matcher(input); + var matcher = BAD_SEMVER.matcher(input); if (!matcher.find() || matcher.start() != 0) { throw new IllegalArgumentException("Version must start with " + BAD_SEMVER.pattern()); } - String major = matcher.group(1); - String minor = matcher.group(2); + var major = matcher.group(1); + var minor = matcher.group(2); return badSemver(Integer.parseInt(major), Integer.parseInt(minor)); } 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..abbd0918fa 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 @@ -18,7 +18,6 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.nio.file.Path; import java.nio.file.StandardCopyOption; import javax.annotation.Nullable; @@ -95,7 +94,7 @@ public void performAction(InputChanges inputs) throws Exception { @VisibleForTesting void processInputFile(@Nullable GitRatchet ratchet, Formatter formatter, File input) throws IOException { - File output = getOutputFile(input); + var output = getOutputFile(input); getLogger().debug("Applying format to {} and writing to {}", input, output); PaddedCell.DirtyState dirtyState; if (ratchet != null && ratchet.isClean(getProjectDir().get().getAsFile(), getRootTreeSha(), input)) { @@ -115,7 +114,7 @@ void processInputFile(@Nullable GitRatchet ratchet, Formatter formatter, File in } else if (dirtyState.didNotConverge()) { getLogger().warn("Skipping '{}' because it does not converge. Run {@code spotlessDiagnose} to understand why", input); } else { - Path parentDir = output.toPath().getParent(); + var parentDir = output.toPath().getParent(); if (parentDir == null) { throw new IllegalStateException("Every file has a parent folder. But not: " + output); } @@ -129,7 +128,7 @@ void processInputFile(@Nullable GitRatchet ratchet, Formatter formatter, File in } private void deletePreviousResult(File input) throws IOException { - File output = getOutputFile(input); + var output = getOutputFile(input); if (output.isDirectory()) { getFs().delete(d -> d.delete(output)); } else { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java index 9f1d04abfd..87bab0a7bf 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java @@ -60,7 +60,7 @@ public TypescriptFormatExtension tsfmt(String version) { /** Creates a {@code TypescriptFormatExtension} using exactly the specified npm packages. */ public TypescriptFormatExtension tsfmt(Map devDependencies) { - TypescriptFormatExtension tsfmt = new TypescriptFormatExtension(devDependencies); + var tsfmt = new TypescriptFormatExtension(devDependencies); addStep(tsfmt.createStep()); return tsfmt; } @@ -188,7 +188,7 @@ public TypescriptEslintConfig eslint(String version) { } public TypescriptEslintConfig eslint(Map devDependencies) { - TypescriptEslintConfig eslint = new TypescriptEslintConfig(devDependencies); + var eslint = new TypescriptEslintConfig(devDependencies); addStep(eslint.createStep()); return eslint; } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/Antlr4ExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/Antlr4ExtensionTest.java index 2e3a2975e9..8d3de4228a 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/Antlr4ExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/Antlr4ExtensionTest.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. @@ -56,12 +56,12 @@ void applyUsingCustomVersion() throws IOException { } private void assertAppliedFormat(String... buildScript) throws IOException { - String testFile = "src/main/antlr4/Hello.g4"; + var testFile = "src/main/antlr4/Hello.g4"; setFile("build.gradle").toLines(buildScript); - String unformatted = "antlr4/Hello.unformatted.g4"; - String formatted = "antlr4/Hello.formatted.g4"; + var unformatted = "antlr4/Hello.unformatted.g4"; + var formatted = "antlr4/Hello.formatted.g4"; setFile(testFile).toResource(unformatted); gradleRunner().withArguments("spotlessApply").build(); 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..7f7a059e15 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. @@ -99,20 +99,20 @@ private Bundle create(File... files) throws IOException { } private Bundle create(List files) throws IOException { - Bundle bundle = new Bundle("underTest"); + var bundle = new Bundle("underTest"); bundle.task.setLineEndingsPolicy(LineEnding.UNIX.createPolicy()); bundle.task.setTarget(files); return bundle; } private void assertCheckFailure(Bundle spotless, String... expectedLines) throws Exception { - String msg = spotless.checkFailureMsg(); + var msg = spotless.checkFailureMsg(); - String firstLine = "The following files had format violations:\n"; - String lastLine = "\n" + EXPECTED_RUN_SPOTLESS_APPLY_SUGGESTION; + var firstLine = "The following files had format violations:\n"; + var lastLine = "\n" + EXPECTED_RUN_SPOTLESS_APPLY_SUGGESTION; Assertions.assertThat(msg).startsWith(firstLine).endsWith(lastLine); - String middle = msg.substring(firstLine.length(), msg.length() - lastLine.length()); + var middle = msg.substring(firstLine.length(), msg.length() - lastLine.length()); String expectedMessage = StringPrinter.buildStringFromLines(expectedLines); Assertions.assertThat(middle).isEqualTo(expectedMessage.substring(0, expectedMessage.length() - 1)); } @@ -138,13 +138,13 @@ void lineEndingProblem() throws Exception { @Test void customRunToFixMessage() throws Exception { Bundle task = create(setFile("testFile").toContent("A\r\nB\r\nC\r\n")); - String customMessage = "Formatting issues detected, please read automatic-code-formatting.txt and correct."; + var customMessage = "Formatting issues detected, please read automatic-code-formatting.txt and correct."; task.check.getRunToFixMessage().set(customMessage); - String msg = task.checkFailureMsg(); + var msg = task.checkFailureMsg(); - String firstLine = "The following files had format violations:\n"; - String lastLine = "\n" + customMessage; + var firstLine = "The following files had format violations:\n"; + var lastLine = "\n" + customMessage; Assertions.assertThat(msg).startsWith(firstLine).endsWith(lastLine); } @@ -152,7 +152,7 @@ void customRunToFixMessage() throws Exception { void whitespaceProblem() throws Exception { Bundle spotless = create(setFile("testFile").toContent("A \nB\t\nC \n")); spotless.task.addStep(FormatterStep.createNeverUpToDate("trimTrailing", input -> { - Pattern pattern = Pattern.compile("[ \t]+$", Pattern.UNIX_LINES | Pattern.MULTILINE); + var pattern = Pattern.compile("[ \t]+$", Pattern.UNIX_LINES | Pattern.MULTILINE); return pattern.matcher(input).replaceAll(""); })); assertCheckFailure(spotless, @@ -188,11 +188,11 @@ void multipleFiles() throws Exception { @Test void manyFiles() throws Exception { List testFiles = new ArrayList<>(); - for (int i = 0; i < 9 + DiffMessageFormatter.MAX_FILES_TO_LIST - 1; ++i) { - String fileName = String.format("%02d", i) + ".txt"; + for (var i = 0; i < 9 + DiffMessageFormatter.MAX_FILES_TO_LIST - 1; ++i) { + var fileName = String.format("%02d", i) + ".txt"; testFiles.add(setFile(fileName).toContent("1\r\n2\r\n")); } - Bundle spotless = create(testFiles); + var spotless = create(testFiles); assertCheckFailure(spotless, " 00.txt", " @@ -1,2 +1,2 @@", @@ -262,11 +262,11 @@ void manyFiles() throws Exception { @Test void manyManyFiles() throws Exception { List testFiles = new ArrayList<>(); - for (int i = 0; i < 9 + DiffMessageFormatter.MAX_FILES_TO_LIST; ++i) { - String fileName = String.format("%02d", i) + ".txt"; + for (var i = 0; i < 9 + DiffMessageFormatter.MAX_FILES_TO_LIST; ++i) { + var fileName = String.format("%02d", i) + ".txt"; testFiles.add(setFile(fileName).toContent("1\r\n2\r\n")); } - Bundle spotless = create(testFiles); + var spotless = create(testFiles); assertCheckFailure(spotless, " 00.txt", " @@ -1,2 +1,2 @@", @@ -326,8 +326,8 @@ void manyManyFiles() throws Exception { @Test void longFile() throws Exception { - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < 1000; ++i) { + var builder = new StringBuilder(); + for (var i = 0; i < 1000; ++i) { builder.append(i); builder.append("\r\n"); } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ErrorShouldRethrowTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ErrorShouldRethrowTest.java index d1ced01609..fc73b0cc45 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ErrorShouldRethrowTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ErrorShouldRethrowTest.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. @@ -130,13 +130,13 @@ private void runWithFailure(String expectedToStartWith) throws Exception { private void assertResultAndMessages(BuildResult result, TaskOutcome outcome, String expectedToStartWith) { String output = result.getOutput(); - int register = output.indexOf(":spotlessInternalRegisterDependencies"); - int firstNewlineAfterThat = output.indexOf('\n', register + 1); - String useThisToMatch = output.substring(firstNewlineAfterThat); + var register = output.indexOf(":spotlessInternalRegisterDependencies"); + var firstNewlineAfterThat = output.indexOf('\n', register + 1); + var useThisToMatch = output.substring(firstNewlineAfterThat); int numNewlines = CharMatcher.is('\n').countIn(expectedToStartWith); List actualLines = Splitter.on('\n').splitToList(LineEnding.toUnix(useThisToMatch.trim())); - String actualStart = String.join("\n", actualLines.subList(0, numNewlines + 1)); + var actualStart = String.join("\n", actualLines.subList(0, numNewlines + 1)); Assertions.assertThat(actualStart).isEqualTo(expectedToStartWith); Assertions.assertThat(outcomes(result, outcome).size() + outcomes(result, TaskOutcome.UP_TO_DATE).size() + outcomes(result, TaskOutcome.NO_SOURCE).size()) .isEqualTo(outcomes(result).size()); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FileTreeTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FileTreeTest.java index bd9800a6c1..984cf470a9 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FileTreeTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FileTreeTest.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. @@ -42,7 +42,7 @@ void fileTree() throws IOException { @Test void absolutePathDoesntWork() throws IOException { File someFile = setFile("someFolder/someFile").toContent(""); - File someFolder = someFile.getParentFile(); + var someFolder = someFile.getParentFile(); fileTree.exclude(someFolder.getAbsolutePath()); Assertions.assertThat(fileTree).containsExactlyInAnyOrder(someFile); } @@ -50,7 +50,7 @@ void absolutePathDoesntWork() throws IOException { @Test void relativePathDoes() throws IOException { File someFile = setFile("someFolder/someFile").toContent(""); - File someFolder = someFile.getParentFile(); + var someFolder = someFile.getParentFile(); fileTree.exclude(relativize(rootFolder(), someFolder)); Assertions.assertThat(fileTree).containsExactlyInAnyOrder(); } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FormatTaskTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FormatTaskTest.java index 8985cd7a14..4c55a61f9c 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FormatTaskTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FormatTaskTest.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. @@ -47,7 +47,7 @@ public BuildServiceParameters.None getParameters() { @Test void testLineEndings() throws Exception { File testFile = setFile("testFile").toContent("\r\n"); - File outputFile = new File(spotlessTask.getOutputDirectory(), "testFile"); + var outputFile = new File(spotlessTask.getOutputDirectory(), "testFile"); spotlessTask.setTarget(Collections.singleton(testFile)); Tasks.execute(spotlessTask); @@ -58,7 +58,7 @@ void testLineEndings() throws Exception { @Test void testStep() throws Exception { File testFile = setFile("testFile").toContent("apple"); - File outputFile = new File(spotlessTask.getOutputDirectory(), "testFile"); + var outputFile = new File(spotlessTask.getOutputDirectory(), "testFile"); spotlessTask.setTarget(Collections.singleton(testFile)); spotlessTask.addStep(FormatterStep.createNeverUpToDate("double-p", content -> content.replace("pp", "p"))); 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..9fa5324fd6 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,9 +97,9 @@ private String filename(String name) { private void writeState(String state) throws IOException { for (char c : state.toCharArray()) { - String letter = new String(new char[]{c}); - boolean exists = new File(rootFolder(), filename(letter)).exists(); - boolean needsChanging = exists && !read(filename(letter)).trim().equals(letter); + var letter = new String(new char[]{c}); + var exists = new File(rootFolder(), filename(letter)).exists(); + var needsChanging = exists && !read(filename(letter)).trim().equals(letter); if (!exists || needsChanging) { setFile(filename(letter)).toContent(letter); } @@ -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}); + var letter = new String(new char[]{c}); if (Character.isLowerCase(c)) { assertEquals(letter.toLowerCase(Locale.ROOT), read(filename(letter)).trim()); } else { @@ -126,14 +126,14 @@ private void checkRanAgainst(String... ranAgainst) throws IOException { } private AbstractStringAssert checkRanAgainstNoneButError() throws IOException { - String console = taskRanAgainst("spotlessCheck"); + var console = taskRanAgainst("spotlessCheck"); return Assertions.assertThat(console); } private String taskRanAgainst(String task, String... ranAgainst) throws IOException { pauseForFilesystem(); String console = StringPrinter.buildString(Errors.rethrow().wrap(printer -> { - boolean expectFailure = task.equals("spotlessCheck") && !isClean(); + var expectFailure = task.equals("spotlessCheck") && !isClean(); if (expectFailure) { gradleRunner().withArguments(task).forwardStdOutput(printer.toWriter()).forwardStdError(printer.toWriter()).buildAndFail(); } else { @@ -142,7 +142,7 @@ private String taskRanAgainst(String task, String... ranAgainst) throws IOExcept })); SortedSet added = new TreeSet<>(); for (String line : console.split("\n")) { - String trimmed = line.trim(); + var trimmed = line.trim(); if (trimmed.startsWith("<") && trimmed.endsWith(">")) { added.add(trimmed.substring(1, trimmed.length() - 1)); } @@ -152,7 +152,7 @@ private String taskRanAgainst(String task, String... ranAgainst) throws IOExcept } private String concat(Iterable iterable) { - StringBuilder result = new StringBuilder(); + var result = new StringBuilder(); for (String item : iterable) { result.append(item); } 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..c75befd317 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 @@ -154,8 +154,8 @@ protected void iterateFiles(Predicate subpathsToInclude, BiConsumer iterator = files.listIterator(files.size()); int rootLength = rootFolder().getAbsolutePath().length() + 1; while (iterator.hasPrevious()) { - File file = iterator.previous(); - String subPath = file.getAbsolutePath().substring(rootLength); + var file = iterator.previous(); + var subPath = file.getAbsolutePath().substring(rootLength); if (subpathsToInclude.test(subPath)) { consumer.accept(subPath, file); } @@ -191,7 +191,7 @@ private void taskIsUpToDate(String task, boolean upToDate) throws IOException { List expected = outcomes(buildResult, upToDate ? TaskOutcome.UP_TO_DATE : TaskOutcome.SUCCESS); List notExpected = outcomes(buildResult, upToDate ? TaskOutcome.SUCCESS : TaskOutcome.UP_TO_DATE); - boolean everythingAsExpected = !expected.isEmpty() && notExpected.isEmpty() && buildResult.getTasks().size() - 1 == expected.size(); + var everythingAsExpected = !expected.isEmpty() && notExpected.isEmpty() && buildResult.getTasks().size() - 1 == expected.size(); if (!everythingAsExpected) { fail("Expected all tasks to be " + (upToDate ? TaskOutcome.UP_TO_DATE : TaskOutcome.SUCCESS) + ", but instead was\n" + buildResultToString(buildResult)); } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyExtensionTest.java index b9c7d2f66e..103bcb934b 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyExtensionTest.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. @@ -37,7 +37,7 @@ void excludeJava() throws IOException { } private void testIncludeExcludeOption(boolean excludeJava) throws IOException { - String excludeStatement = excludeJava ? "excludeJava()" : ""; + var excludeStatement = excludeJava ? "excludeJava()" : ""; setFile("build.gradle").toLines( "plugins {", " id 'com.diffplug.spotless'", diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyGradleExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyGradleExtensionTest.java index 7f4d593a9c..8f7b624065 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyGradleExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyGradleExtensionTest.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. @@ -35,7 +35,7 @@ void customTarget() throws IOException { } private void testTarget(boolean useDefaultTarget) throws IOException { - String target = useDefaultTarget ? "" : "target 'other.gradle'"; + var target = useDefaultTarget ? "" : "target 'other.gradle'"; String buildContent = StringPrinter.buildStringFromLines( "plugins {", " id 'com.diffplug.spotless'", 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..6a288f4cef 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. @@ -58,8 +58,8 @@ void before() throws IOException { } private void runWith(String... arguments) throws IOException { - StringBuilder output = new StringBuilder(); - StringBuilder error = new StringBuilder(); + var output = new StringBuilder(); + var error = new StringBuilder(); try (Writer outputWriter = new StringPrinter(output::append).toWriter(); Writer errorWriter = new StringPrinter(error::append).toWriter();) { gradleRunner() diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/JavascriptExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/JavascriptExtensionTest.java index f1b00706d3..48c9415731 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/JavascriptExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/JavascriptExtensionTest.java @@ -78,7 +78,7 @@ void eslintAllowsToSpecifyEslintVersionForJavascript() throws IOException { @Test void esllintAllowsToSpecifyInlineConfig() throws IOException { - final String eslintConfigJs = String.join("\n", + final var eslintConfigJs = String.join("\n", "{", " env: {", " browser: true,", @@ -163,7 +163,7 @@ class EslintPopularJsStyleGuideTests extends GradleIntegrationHarness { @ValueSource(strings = {"airbnb", "google", "standard", "xo"}) void formattingUsingStyleguide(String styleguide) throws Exception { - final String styleguidePath = "npm/eslint/javascript/styleguide/" + styleguide + "/"; + final var styleguidePath = "npm/eslint/javascript/styleguide/" + styleguide + "/"; setFile(".eslintrc.js").toResource(styleguidePath + ".eslintrc.js"); setFile("build.gradle").toLines( diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/LicenseHeaderTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/LicenseHeaderTest.java index 4b0784832f..be826de58f 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/LicenseHeaderTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/LicenseHeaderTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-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. @@ -86,7 +86,7 @@ void filterByContentPatternTest() throws IOException { setFile(TEST_JAVA).toContent(CONTENT); gradleRunner().withArguments("spotlessApply", "--stacktrace").forwardOutput().build(); assertFile(TEST_JAVA).hasContent("/** New License Header */\n" + CONTENT); - String multipleLicenseHeaderConfiguration = "licenseHeader('/** Base License Header */').named('PrimaryHeaderLicense').onlyIfContentMatches('Best')\n" + + var multipleLicenseHeaderConfiguration = "licenseHeader('/** Base License Header */').named('PrimaryHeaderLicense').onlyIfContentMatches('Best')\n" + "licenseHeader('/** Alternate License Header */').named('SecondaryHeaderLicense').onlyIfContentMatches('.*Test.+')"; setLicenseStep(multipleLicenseHeaderConfiguration); setFile(TEST_JAVA).toContent("/** 2003 */\n" + CONTENT); 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 98761b472a..cac9235cca 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 @@ -26,11 +26,11 @@ class MultiProjectTest extends GradleIntegrationHarness { private static int N = 100; private void createNSubprojects() throws IOException { - for (int i = 0; i < N; ++i) { + for (var i = 0; i < N; ++i) { createSubproject(Integer.toString(i)); } String settings = StringPrinter.buildString(printer -> { - for (int i = 0; i < N; ++i) { + for (var i = 0; i < N; ++i) { printer.println("include '" + 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..3f10851c1b 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,7 +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; + var cacheDir = DEFAULT_DIR_FOR_NPM_INSTALL_CACHE_DO_NEVER_WRITE_TO_THIS; BuildResult result = runPhpPrettierOnDir(dir1, cacheDir); Assertions.assertThat(result.getOutput()) .doesNotContain("Using cached node_modules for") @@ -82,7 +82,7 @@ void prettierDoesNotCacheNodeModulesIfNotExplicitlyEnabled() throws IOException @Order(1) void prettierCachesNodeModuleInGlobalInstallCacheDir() throws IOException { File dir1 = newFolder("npm-prettier-global-1"); - File cacheDir = pertainingCacheDir; + var cacheDir = pertainingCacheDir; BuildResult result = runPhpPrettierOnDir(dir1, cacheDir); Assertions.assertThat(result.getOutput()) .doesNotContainPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E") @@ -93,7 +93,7 @@ void prettierCachesNodeModuleInGlobalInstallCacheDir() throws IOException { @Order(2) void prettierUsesCachedNodeModulesFromGlobalInstallCacheDir() throws IOException { File dir2 = newFolder("npm-prettier-global-2"); - File cacheDir = pertainingCacheDir; + var cacheDir = pertainingCacheDir; BuildResult result = runPhpPrettierOnDir(dir2, cacheDir); Assertions.assertThat(result.getOutput()) .containsPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E") @@ -101,8 +101,8 @@ void prettierUsesCachedNodeModulesFromGlobalInstallCacheDir() throws IOException } private BuildResult runPhpPrettierOnDir(File projDir, File cacheDir) throws IOException { - String baseDir = projDir.getName(); - String cacheDirEnabled = cacheDirEnabledStringForCacheDir(cacheDir); + var baseDir = projDir.getName(); + var cacheDirEnabled = cacheDirEnabledStringForCacheDir(cacheDir); setFile(baseDir + "/build.gradle").toLines( "plugins {", " id 'com.diffplug.spotless'", @@ -131,7 +131,7 @@ private BuildResult runPhpPrettierOnDir(File projDir, File cacheDir) throws IOEx @Order(3) void tsfmtCachesNodeModuleInGlobalInstallCacheDir() throws IOException { File dir1 = newFolder("npm-tsfmt-global-1"); - File cacheDir = pertainingCacheDir; + var cacheDir = pertainingCacheDir; BuildResult result = runTsfmtOnDir(dir1, cacheDir); Assertions.assertThat(result.getOutput()) .doesNotContainPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E") @@ -142,7 +142,7 @@ void tsfmtCachesNodeModuleInGlobalInstallCacheDir() throws IOException { @Order(4) void tsfmtUsesCachedNodeModulesFromGlobalInstallCacheDir() throws IOException { File dir2 = newFolder("npm-tsfmt-global-2"); - File cacheDir = pertainingCacheDir; + var cacheDir = pertainingCacheDir; BuildResult result = runTsfmtOnDir(dir2, cacheDir); Assertions.assertThat(result.getOutput()) .containsPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E") @@ -159,8 +159,8 @@ void tsfmtDoesNotCacheNodeModulesIfNotExplicitlyEnabled() throws IOException { } private BuildResult runTsfmtOnDir(File projDir, File cacheDir) throws IOException { - String baseDir = projDir.getName(); - String cacheDirEnabled = cacheDirEnabledStringForCacheDir(cacheDir); + var baseDir = projDir.getName(); + var cacheDirEnabled = cacheDirEnabledStringForCacheDir(cacheDir); setFile(baseDir + "/build.gradle").toLines( "plugins {", " id 'com.diffplug.spotless'", @@ -185,7 +185,7 @@ private BuildResult runTsfmtOnDir(File projDir, File cacheDir) throws IOExceptio @Order(5) void eslintCachesNodeModuleInGlobalInstallCacheDir() throws IOException { File dir1 = newFolder("npm-eslint-global-1"); - File cacheDir = pertainingCacheDir; + var cacheDir = pertainingCacheDir; BuildResult result = runEslintOnDir(dir1, cacheDir); Assertions.assertThat(result.getOutput()) .doesNotContainPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E") @@ -196,7 +196,7 @@ void eslintCachesNodeModuleInGlobalInstallCacheDir() throws IOException { @Order(6) void eslintUsesCachedNodeModulesFromGlobalInstallCacheDir() throws IOException { File dir2 = newFolder("npm-eslint-global-2"); - File cacheDir = pertainingCacheDir; + var cacheDir = pertainingCacheDir; BuildResult result = runEslintOnDir(dir2, cacheDir); Assertions.assertThat(result.getOutput()) .containsPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E") @@ -214,8 +214,8 @@ void eslintDoesNotCacheNodeModulesIfNotExplicitlyEnabled() throws IOException { } private BuildResult runEslintOnDir(File projDir, File cacheDir) throws IOException { - String baseDir = projDir.getName(); - String cacheDirEnabled = cacheDirEnabledStringForCacheDir(cacheDir); + var baseDir = projDir.getName(); + var cacheDirEnabled = cacheDirEnabledStringForCacheDir(cacheDir); setFile(baseDir + "/.eslintrc.js").toResource("npm/eslint/typescript/custom_rules/.eslintrc.js"); setFile(baseDir + "/build.gradle").toLines( 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..21292e5f20 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. @@ -131,10 +131,10 @@ private Bundle diverge() throws IOException { @Test void paddedCellFormat() throws Exception { - Bundle wellbehaved = wellbehaved(); - Bundle cycle = cycle(); - Bundle converge = converge(); - Bundle diverge = diverge(); + var wellbehaved = wellbehaved(); + var cycle = cycle(); + var converge = converge(); + var diverge = diverge(); wellbehaved.format(); cycle.format(); @@ -149,10 +149,10 @@ void paddedCellFormat() throws Exception { @Test void paddedCellApplyCheck() throws Exception { - Bundle wellbehaved = wellbehaved(); - Bundle cycle = cycle(); - Bundle converge = converge(); - Bundle diverge = diverge(); + var wellbehaved = wellbehaved(); + var cycle = cycle(); + var converge = converge(); + var diverge = diverge(); wellbehaved.apply(); cycle.apply(); @@ -203,9 +203,9 @@ void diagnose() throws Exception { } private void assertFolderContents(String subfolderName, String... files) throws IOException { - File subfolder = new File(rootFolder(), subfolderName); + var subfolder = new File(rootFolder(), subfolderName); Assertions.assertTrue(subfolder.isDirectory()); - String asList = String.join("\n", Arrays.asList(files)); + var asList = String.join("\n", Arrays.asList(files)); Assertions.assertEquals(StringPrinter.buildStringFromLines(files).trim(), asList); } @@ -231,7 +231,7 @@ void paddedCellCheckConvergeFailureMsg() throws IOException { } private void assertFailureMessage(Bundle bundle, String... expectedOutput) { - String msg = bundle.checkFailureMsg(); + var msg = bundle.checkFailureMsg(); String expected = StringPrinter.buildStringFromLines(expectedOutput).trim(); Assertions.assertEquals(expected, msg); } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessTaskImplTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessTaskImplTest.java index fc7fab9980..cd5c501863 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessTaskImplTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessTaskImplTest.java @@ -15,7 +15,6 @@ */ package com.diffplug.gradle.spotless; -import java.io.File; import java.nio.file.Paths; import org.assertj.core.api.Assertions; @@ -32,13 +31,13 @@ public void testThrowsMessageContainsFilename() throws Exception { SpotlessTaskImpl task = Mockito.mock(SpotlessTaskImpl.class, Mockito.CALLS_REAL_METHODS); Mockito.when(task.getLogger()).thenReturn(Mockito.mock(Logger.class)); - File projectDir = Paths.get("unitTests", "projectDir").toFile(); + var projectDir = Paths.get("unitTests", "projectDir").toFile(); DirectoryProperty projectDirProperty = Mockito.mock(DirectoryProperty.class, Mockito.RETURNS_DEEP_STUBS); Mockito.when(projectDirProperty.get().getAsFile()).thenReturn(projectDir); Mockito.when(task.getProjectDir()).thenReturn(projectDirProperty); - File input = Paths.get("unitTests", "projectDir", "someInput").toFile(); + var input = Paths.get("unitTests", "projectDir", "someInput").toFile(); Formatter formatter = Mockito.mock(Formatter.class); Assertions.assertThatThrownBy(() -> task.processInputFile(null, formatter, input)).hasMessageContaining(input.toString()); diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java index 2c0d6e35e6..a0a559e88e 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java @@ -258,7 +258,7 @@ private List collectFiles(FormatterFactory formatterFactory, FormatterConf if (filePatterns == null || filePatterns.isEmpty()) { return files; } - final String[] includePatterns = this.filePatterns.split(","); + final var includePatterns = this.filePatterns.split(","); final List compiledIncludePatterns = Arrays.stream(includePatterns) .map(Pattern::compile) .collect(Collectors.toList()); diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FileLocator.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FileLocator.java index 7ea998dc95..0c0e2e3d81 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FileLocator.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FileLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-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,12 +51,12 @@ public File locateFile(String path) { return null; } - File localFile = new File(path); + var localFile = new File(path); if (localFile.exists() && localFile.isFile()) { return localFile; } - String outputFile = tmpOutputFileName(path); + var outputFile = tmpOutputFileName(path); try { return resourceManager.getResourceAsFile(path, outputFile); } catch (ResourceNotFoundException e) { @@ -76,8 +76,8 @@ public File getBuildDir() { private static String tmpOutputFileName(String path) { String extension = FileUtils.extension(path); - byte[] pathHash = hash(path); - String pathBase64 = Base64.getEncoder().encodeToString(pathHash); + var pathHash = hash(path); + var pathBase64 = Base64.getEncoder().encodeToString(pathHash); return TMP_RESOURCE_FILE_PREFIX + pathBase64 + '.' + extension; } 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..ca09b1675b 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 @@ -102,7 +102,7 @@ public final Formatter newFormatter(Supplier> filesToFormat, Form formatterSteps.add(pair.out()); } - String formatterName = this.getClass().getSimpleName(); + var formatterName = this.getClass().getSimpleName(); return Formatter.builder() .name(formatterName) .encoding(formatterEncoding) diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/GitRatchetMaven.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/GitRatchetMaven.java index f68ac295f6..eea7f3dc4f 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/GitRatchetMaven.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/GitRatchetMaven.java @@ -1,5 +1,5 @@ /* - * Copyright 2020 DiffPlug + * Copyright 2020-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ import java.io.File; import java.io.IOException; -import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; import java.util.Set; @@ -64,7 +63,7 @@ Iterable getDirtyFiles(File baseDir, String ratchetFrom) throws IOExcept indexDiff.diff(); String workTreePath = repository.getWorkTree().getPath(); - Path baseDirPath = Paths.get(baseDir.getPath()); + var baseDirPath = Paths.get(baseDir.getPath()); Set dirtyPaths = new HashSet<>(indexDiff.getChanged()); dirtyPaths.addAll(indexDiff.getAdded()); diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java index 8330319cfb..fefe6a8292 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java @@ -66,8 +66,8 @@ static FileIndex read(FileIndexConfig config, Log log) { return emptyIndexFallback(config); } - try (BufferedReader reader = newBufferedReader(indexFile, UTF_8)) { - String firstLine = reader.readLine(); + try (var reader = newBufferedReader(indexFile, UTF_8)) { + var firstLine = reader.readLine(); if (firstLine == null) { log.info("Index file is empty. Fallback to an empty index"); return emptyIndexFallback(config); @@ -90,7 +90,7 @@ static FileIndex read(FileIndexConfig config, Log log) { static void delete(FileIndexConfig config, Log log) { Path indexFile = config.getIndexFile(); - boolean deleted = false; + var deleted = false; try { deleted = Files.deleteIfExists(indexFile); } catch (IOException e) { @@ -106,12 +106,12 @@ Instant getLastModifiedTime(Path file) { if (!file.startsWith(projectDir)) { return null; } - Path relativeFile = projectDir.relativize(file); + var relativeFile = projectDir.relativize(file); return fileToLastModifiedTime.get(relativeFile); } void setLastModifiedTime(Path file, Instant time) { - Path relativeFile = projectDir.relativize(file); + var relativeFile = projectDir.relativize(file); fileToLastModifiedTime.put(relativeFile, time); modified = true; } @@ -127,7 +127,7 @@ void write() { } ensureParentDirExists(); - try (PrintWriter writer = new PrintWriter(newBufferedWriter(indexFile, UTF_8, CREATE, TRUNCATE_EXISTING))) { + try (var writer = new PrintWriter(newBufferedWriter(indexFile, UTF_8, CREATE, TRUNCATE_EXISTING))) { writer.println(pluginFingerprint.value()); for (Entry entry : fileToLastModifiedTime.entrySet()) { @@ -139,7 +139,7 @@ void write() { } private void ensureParentDirExists() { - Path parentDir = indexFile.getParent(); + var parentDir = indexFile.getParent(); if (parentDir == null) { throw new IllegalStateException("Index file does not have a parent dir: " + indexFile); } @@ -152,22 +152,22 @@ private void ensureParentDirExists() { private static Content readIndexContent(BufferedReader reader, Path projectDir, Log log) throws IOException { Map fileToLastModifiedTime = new TreeMap<>(); - boolean needsRewrite = false; + var needsRewrite = false; String line; while ((line = reader.readLine()) != null) { - int separatorIndex = line.lastIndexOf(SEPARATOR); + var separatorIndex = line.lastIndexOf(SEPARATOR); if (separatorIndex == -1) { throw new IOException("Incorrect index file. No separator found in '" + line + "'"); } - Path relativeFile = Paths.get(line.substring(0, separatorIndex)); - Path absoluteFile = projectDir.resolve(relativeFile); + var relativeFile = Paths.get(line.substring(0, separatorIndex)); + var absoluteFile = projectDir.resolve(relativeFile); if (Files.notExists(absoluteFile)) { log.info("File stored in the index does not exist: " + relativeFile); needsRewrite = true; } else { - Instant lastModifiedTime = parseLastModifiedTime(line, separatorIndex); + var lastModifiedTime = parseLastModifiedTime(line, separatorIndex); fileToLastModifiedTime.put(relativeFile, lastModifiedTime); } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/IndexBasedChecker.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/IndexBasedChecker.java index 1ae32a4b60..3f693ea438 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/IndexBasedChecker.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/IndexBasedChecker.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. @@ -54,7 +54,7 @@ public boolean isUpToDate(Path file) { @Override public void setUpToDate(Path file) { - Instant lastModified = lastModifiedTime(file); + var lastModified = lastModifiedTime(file); if (Instant.MIN.equals(lastModified) || Instant.MAX.equals(lastModified)) { // FileTime can store timestamps further in the past/future than Instant. // Such timestamps are saturated to Instant.MIN/Instant.MAX. diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/ObjectDigestOutputStream.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/ObjectDigestOutputStream.java index 8ff2c03c9f..6120283a6a 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/ObjectDigestOutputStream.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/ObjectDigestOutputStream.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. @@ -40,7 +40,7 @@ byte[] digest() { } private static DigestOutputStream createDigestOutputStream() { - OutputStream nullOutputStream = new OutputStream() { + var nullOutputStream = new OutputStream() { @Override public void write(int b) {} }; diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/PluginFingerprint.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/PluginFingerprint.java index 34a01e235a..060134f539 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/PluginFingerprint.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/PluginFingerprint.java @@ -46,7 +46,7 @@ private PluginFingerprint(String value) { static PluginFingerprint from(MavenProject project, Iterable formatters) { Plugin spotlessPlugin = findSpotlessPlugin(project); byte[] digest = digest(spotlessPlugin, formatters); - String value = Base64.getEncoder().encodeToString(digest); + var value = Base64.getEncoder().encodeToString(digest); return new PluginFingerprint(value); } @@ -70,7 +70,7 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } - PluginFingerprint that = (PluginFingerprint) o; + var that = (PluginFingerprint) o; return value.equals(that.value); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecking.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecking.java index f044b847c9..70adff5348 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecking.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecking.java @@ -40,7 +40,7 @@ public Path getIndexFile() { } public static UpToDateChecking enabled() { - UpToDateChecking upToDateChecking = new UpToDateChecking(); + var upToDateChecking = new UpToDateChecking(); upToDateChecking.enabled = true; return upToDateChecking; } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java index b0692446b7..b949445602 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java @@ -85,7 +85,7 @@ public void addCleanthat(CleanthatJava cleanthat) { } private static String fileMask(Path path) { - String dir = path.toString(); + var dir = path.toString(); if (!dir.endsWith(File.separator)) { dir += File.separator; } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Gson.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Gson.java index fb5a38e890..d392ddc059 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Gson.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Gson.java @@ -40,7 +40,7 @@ public class Gson implements FormatterStepFactory { @Override public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) { - int indentSpaces = this.indentSpaces; + var indentSpaces = this.indentSpaces; return GsonStep.create(new GsonConfig(sortByKeys, escapeHtml, indentSpaces, version), stepConfig.getProvisioner()); } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Simple.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Simple.java index f1cc114da2..484e17bf6e 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Simple.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Simple.java @@ -29,7 +29,7 @@ public class Simple implements FormatterStepFactory { @Override public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) { - int indentSpaces = this.indentSpaces; + var indentSpaces = this.indentSpaces; return JsonSimpleStep.create(indentSpaces, stepConfig.getProvisioner()); } } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/FileLocatorTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/FileLocatorTest.java index 9a80d07f1a..ea64e0b8a2 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/FileLocatorTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/FileLocatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,14 +66,14 @@ void locatePropertiesFile() throws Exception { @Test void locateConfFileWithIncorrectSeparators() throws Exception { - String oppositeSeparator = "/".equals(File.separator) ? "\\" : "/"; - String path = "tmp" + oppositeSeparator + "configs" + oppositeSeparator + "hello.conf"; + var oppositeSeparator = "/".equals(File.separator) ? "\\" : "/"; + var path = "tmp" + oppositeSeparator + "configs" + oppositeSeparator + "hello.conf"; testFileLocator(path, "conf"); } private void testFileLocator(String path, String extension) throws Exception { - File tmpOutputFile = new File("tmp-file"); + var tmpOutputFile = new File("tmp-file"); when(resourceManager.getResourceAsFile(any(), any())).thenReturn(tmpOutputFile); File locatedFile = fileLocator.locateFile(path); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/IncludesExcludesTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/IncludesExcludesTest.java index e8174e35fc..085f53c80c 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/IncludesExcludesTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/IncludesExcludesTest.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,13 +28,13 @@ class IncludesExcludesTest extends MavenIntegrationHarness { @Test void testDefaultIncludesJava() throws Exception { - String unformattedCorrectLocation1 = "src/main/java/test1.java"; - String unformattedCorrectLocation2 = "src/main/java/test2.java"; - String unformattedCorrectLocation3 = "src/test/java/test3.java"; - String unformattedCorrectLocation4 = "src/test/java/test4.java"; - String formattedCorrectLocation = "src/main/java/test5.java"; - String unformattedIncorrectLocation1 = "src/main/my-java/test6.java"; - String unformattedIncorrectLocation2 = "sources/main/java/test7.java"; + var unformattedCorrectLocation1 = "src/main/java/test1.java"; + var unformattedCorrectLocation2 = "src/main/java/test2.java"; + var unformattedCorrectLocation3 = "src/test/java/test3.java"; + var unformattedCorrectLocation4 = "src/test/java/test4.java"; + var formattedCorrectLocation = "src/main/java/test5.java"; + var unformattedIncorrectLocation1 = "src/main/my-java/test6.java"; + var unformattedIncorrectLocation2 = "sources/main/java/test7.java"; writePomWithJavaSteps( "", @@ -64,13 +64,13 @@ void testDefaultIncludesJava() throws Exception { @Test void testDefaultIncludesScala() throws Exception { - String unformattedCorrectLocation1 = "src/main/scala/test1.scala"; - String unformattedCorrectLocation2 = "src/main/scala/test2.sc"; - String unformattedCorrectLocation3 = "src/test/scala/test3.sc"; - String unformattedCorrectLocation4 = "src/test/scala/test4.scala"; - String formattedCorrectLocation = "src/test/scala/test5.scala"; - String unformattedIncorrectLocation1 = "src/main/not-scala/test6.sc"; - String unformattedIncorrectLocation2 = "scala/scala/scala/test7.scala"; + var unformattedCorrectLocation1 = "src/main/scala/test1.scala"; + var unformattedCorrectLocation2 = "src/main/scala/test2.sc"; + var unformattedCorrectLocation3 = "src/test/scala/test3.sc"; + var unformattedCorrectLocation4 = "src/test/scala/test4.scala"; + var formattedCorrectLocation = "src/test/scala/test5.scala"; + var unformattedIncorrectLocation1 = "src/main/not-scala/test6.sc"; + var unformattedIncorrectLocation2 = "scala/scala/scala/test7.scala"; writePomWithScalaSteps(""); @@ -95,10 +95,10 @@ void testDefaultIncludesScala() throws Exception { @Test void testInclude() throws Exception { - String unformattedDefaultLocation1 = "src/main/scala/test1.scala"; - String unformattedDefaultLocation2 = "src/test/scala/test2.scala"; - String unformattedCustomLocation1 = "src/main/my-scala/test3.scala"; - String unformattedCustomLocation2 = "src/test/sc/test4.sc"; + var unformattedDefaultLocation1 = "src/main/scala/test1.scala"; + var unformattedDefaultLocation2 = "src/test/scala/test2.scala"; + var unformattedCustomLocation1 = "src/main/my-scala/test3.scala"; + var unformattedCustomLocation2 = "src/test/sc/test4.sc"; writePomWithScalaSteps( "", @@ -124,10 +124,10 @@ void testInclude() throws Exception { @Test void testExclude() throws Exception { - String unformatted1 = "src/main/scala/test1.scala"; - String unformatted2 = "src/main/scala/test2.sc"; - String unformatted3 = "src/test/scala/test3.scala"; - String unformatted4 = "src/test/scala/test4.sc"; + var unformatted1 = "src/main/scala/test1.scala"; + var unformatted2 = "src/main/scala/test2.sc"; + var unformatted3 = "src/test/scala/test3.scala"; + var unformatted4 = "src/test/scala/test4.sc"; writePomWithScalaSteps( "", diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java index 2891ee3b2c..91a4f5a39f 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java @@ -25,7 +25,6 @@ import java.io.File; import java.io.IOException; import java.io.StringWriter; -import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -179,7 +178,7 @@ protected void writePom(String... configuration) throws IOException { } protected void writePom(String[] executions, String[] configuration, String[] dependencies, String[] plugins) throws IOException { - String pomXmlContent = createPomXmlContent(null, executions, configuration, dependencies, plugins); + var pomXmlContent = createPomXmlContent(null, executions, configuration, dependencies, plugins); setFile("pom.xml").toContent(pomXmlContent); } @@ -229,10 +228,10 @@ protected String createPomXmlContent(String[] build, String[] configuration) thr } protected String createPomXmlContent(String pomTemplate, Map params) throws IOException { - URL url = MavenIntegrationHarness.class.getResource(pomTemplate); + var url = MavenIntegrationHarness.class.getResource(pomTemplate); try (BufferedReader reader = Resources.asCharSource(url, StandardCharsets.UTF_8).openBufferedStream()) { Mustache mustache = mustacheFactory.compile(reader, "pom"); - StringWriter writer = new StringWriter(); + var writer = new StringWriter(); mustache.execute(writer, params); return writer.toString(); } @@ -278,7 +277,7 @@ private static String getSystemProperty(String name) { throw Unhandled.stringException(name); } } - String value = System.getProperty(name); + var value = System.getProperty(name); if (isNullOrEmpty(value)) { fail("System property '" + name + "' is not defined"); } @@ -286,7 +285,7 @@ private static String getSystemProperty(String name) { } protected static String[] groupWithSteps(String group, String[] includes, String... steps) { - String[] result = new String[steps.length + includes.length + 2]; + var result = new String[steps.length + includes.length + 2]; result[0] = "<" + group + ">"; System.arraycopy(includes, 0, result, 1, includes.length); System.arraycopy(steps, 0, result, includes.length + 1, steps.length); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenProvisionerTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenProvisionerTest.java index 5af146c736..337997c2cd 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenProvisionerTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenProvisionerTest.java @@ -39,8 +39,8 @@ void testSingleDependencyIncludingTransitives() throws Exception { } private void assertResolveDependenciesWorks() throws Exception { - String path = "src/main/java/test.java"; - String unformattedContent = "package a;"; + var path = "src/main/java/test.java"; + var unformattedContent = "package a;"; setFile(path).toContent(unformattedContent); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).hasContent(unformattedContent.replace(" ", " ")); 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..9f6e3804dc 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 @@ -59,7 +59,7 @@ public MavenRunner withRunner(ProcessRunner runner) { } public MavenRunner withRemoteDebug(int port) { - String address = (Jvm.version() < 9 ? "" : "*:") + port; + var address = (Jvm.version() < 9 ? "" : "*:") + port; environment.put("MAVEN_OPTS", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=" + address); return this; } @@ -68,7 +68,7 @@ private ProcessRunner.Result run() throws IOException, InterruptedException { Objects.requireNonNull(projectDir, "Need to call withProjectDir() first"); Objects.requireNonNull(args, "Need to call withArguments() first"); // run maven with the given args in the given directory - String argsString = "-e " + String.join(" ", Arrays.asList(args)); + var argsString = "-e " + String.join(" ", Arrays.asList(args)); return runner.shellWinUnix(projectDir, environment, "mvnw " + argsString, "./mvnw " + argsString); } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultiModuleProjectTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultiModuleProjectTest.java index a2d491cb2b..d3696bd7e5 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultiModuleProjectTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultiModuleProjectTest.java @@ -143,7 +143,7 @@ private void createRootPom() throws IOException { List modulesList = new ArrayList<>(); modulesList.add(configSubProject); modulesList.addAll(subProjects.keySet()); - String[] modules = modulesList.toArray(new String[0]); + var modules = modulesList.toArray(new String[0]); Map rootPomParams = buildPomXmlParams(null, null, null, configuration, modules, null, null); setFile("pom.xml").toContent(createPomXmlContent("/multi-module/pom-parent.xml.mustache", rootPomParams)); @@ -160,7 +160,7 @@ private void createConfigSubProject() throws IOException { private void createSubProjects() throws IOException { for (Map.Entry> entry : subProjects.entrySet()) { - String subProjectName = entry.getKey(); + var subProjectName = entry.getKey(); List subProjectFiles = entry.getValue(); String content = createPomXmlContent("/multi-module/pom-child.xml.mustache", singletonMap(CHILD_ID, subProjectName)); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultipleFormatsTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultipleFormatsTest.java index a12aac9986..ce636d0075 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultipleFormatsTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultipleFormatsTest.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. @@ -53,12 +53,12 @@ void testMultipleFormatsWithDifferentIncludes() throws Exception { " ", ""); - String path1 = "src/main/java/test1.java"; - String path2 = "src/main/java/test2.java"; + var path1 = "src/main/java/test1.java"; + var path2 = "src/main/java/test2.java"; - String path3 = "src/main/txt/test1.txt"; - String path4 = "src/main/txt/test2.txt"; - String path5 = "src/main/txt/test3.txt"; + var path3 = "src/main/txt/test1.txt"; + var path4 = "src/main/txt/test2.txt"; + var path5 = "src/main/txt/test3.txt"; setFile(path1).toContent("package test;\npublic class JavaWorld1 {}"); setFile(path2).toContent("package test;\npublic class JavaWorld2 {}"); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpecificFilesTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpecificFilesTest.java index 11cca5994a..b8eeda8433 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpecificFilesTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpecificFilesTest.java @@ -23,14 +23,14 @@ public class SpecificFilesTest extends MavenIntegrationHarness { private String testFile(int number, boolean absolute) throws IOException { - String rel = "src/main/java/test" + number + ".java"; + var rel = "src/main/java/test" + number + ".java"; Path path; if (absolute) { path = Paths.get(rootFolder().getAbsolutePath(), rel); } else { path = Paths.get(rel); } - String result = path.toString(); + var result = path.toString(); if (!isOnWindows()) { return result; } else { diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/antlr4/Antlr4FormatterTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/antlr4/Antlr4FormatterTest.java index 4f1b1c2353..19f4c07074 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/antlr4/Antlr4FormatterTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/antlr4/Antlr4FormatterTest.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. @@ -46,7 +46,7 @@ void applyUsingDefaultVersionSelfclosing() throws Exception { } private void runTest() throws Exception { - String path = "src/main/antlr4/Hello.g4"; + var path = "src/main/antlr4/Hello.g4"; setFile(path).toResource("antlr4/Hello.unformatted.g4"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("antlr4/Hello.formatted.g4"); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/EclipseWtpTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/EclipseWtpTest.java index 9c7385f9be..74b5b5d51f 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/EclipseWtpTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/EclipseWtpTest.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. @@ -31,8 +31,8 @@ void testType() throws Exception { } private void runTest() throws Exception { - String notFormatted = " c"; - String formatted = "\n\t c\n"; + var notFormatted = " c"; + var formatted = "\n\t c\n"; //writePomWithFormatSteps includes java. WTP does not care about file extensions. setFile("src/main/java/test.java").toContent(notFormatted); mavenRunner().withArguments("spotless:apply").runNoError(); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/EndWithNewlineTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/EndWithNewlineTest.java index 1058959f89..8d09e96d6e 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/EndWithNewlineTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/EndWithNewlineTest.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. @@ -37,8 +37,8 @@ void fromContentWithSelfclosingTag() throws Exception { } private void runTest() throws Exception { - String noTrailingNewline = "public class Java {}"; - String hasTrailingNewline = noTrailingNewline + "\n"; + var noTrailingNewline = "public class Java {}"; + var hasTrailingNewline = noTrailingNewline + "\n"; setFile("src/main/java/test.java").toContent(noTrailingNewline); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile("src/main/java/test.java").hasContent(hasTrailingNewline); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/IndentTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/IndentTest.java index b7558cf763..bbb42abc91 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/IndentTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/IndentTest.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. @@ -48,7 +48,7 @@ private void runToSpacesTest() throws Exception { } private void runTest(String source, String target) throws Exception { - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toResource(source); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource(target); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/Jsr223Test.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/Jsr223Test.java index eb1b3b0575..f432d7810f 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/Jsr223Test.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/Jsr223Test.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. @@ -51,7 +51,7 @@ public void groovyFromJarState() throws Exception { } private void runTest(String sourceContent, String targetContent) throws Exception { - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toContent(sourceContent); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).hasContent(targetContent); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LicenseHeaderTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LicenseHeaderTest.java index 92d74bc659..c9026a5850 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LicenseHeaderTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LicenseHeaderTest.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. @@ -35,7 +35,7 @@ void fromFileJava() throws Exception { @Test void fromContentCpp() throws Exception { - String cppLicense = "//my license"; + var cppLicense = "//my license"; writePomWithCppSteps( "src/**", "", @@ -44,8 +44,8 @@ void fromContentCpp() throws Exception { " ", ""); - String path = "src/test/cpp/file.c++"; - String cppContent = "#include "; + var path = "src/test/cpp/file.c++"; + var cppContent = "#include "; setFile(path).toContent(cppContent); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).hasContent(cppLicense + '\n' + cppContent); @@ -61,7 +61,7 @@ void fromContentGroovy() throws Exception { " ", ""); - String path = "src/main/groovy/test.groovy"; + var path = "src/main/groovy/test.groovy"; setFile(path).toResource("license/MissingLicense.test"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("license/HasLicense.test"); @@ -123,7 +123,7 @@ void fromContentKotlin() throws Exception { " ", ""); - String path = "src/main/kotlin/test.kt"; + var path = "src/main/kotlin/test.kt"; String noLicenseHeader = getTestResource("kotlin/licenseheader/KotlinCodeWithoutHeader.test"); setFile(path).toContent(noLicenseHeader); @@ -142,7 +142,7 @@ void unsupportedModuleInfo() throws Exception { } private void runTest() throws Exception { - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toResource("license/MissingLicense.test"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("license/HasLicense.test"); @@ -156,7 +156,7 @@ private void testUnsupportedFile(String file) throws Exception { " ", ""); - String path = "src/main/java/com/diffplug/spotless/" + file; + var path = "src/main/java/com/diffplug/spotless/" + file; setFile(path).toResource("license/" + file + ".test"); mavenRunner().withArguments("spotless:apply").runNoError(); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LineEndingsTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LineEndingsTest.java index 1c99234fcc..e56e8c75ab 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LineEndingsTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LineEndingsTest.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. @@ -44,7 +44,7 @@ private void runToUnixTest() throws Exception { } private void runTest(String sourceContent, String targetContent) throws Exception { - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toContent(sourceContent); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).hasContent(targetContent); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/NativeCmdTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/NativeCmdTest.java index fe1fdd3c6e..5d47a2785a 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/NativeCmdTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/NativeCmdTest.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. @@ -41,7 +41,7 @@ public void fromStdInToStdOut() throws Exception { } private void runTest(String sourceContent, String targetContent) throws Exception { - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toContent(sourceContent); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).hasContent(targetContent); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/ReplaceRegexTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/ReplaceRegexTest.java index e3ce08b359..49c3022e7a 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/ReplaceRegexTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/ReplaceRegexTest.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. @@ -34,7 +34,7 @@ void fromContent() throws Exception { } private void runTest(String sourceContent, String targetContent) throws Exception { - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toContent(sourceContent); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).hasContent(targetContent); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/ReplaceTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/ReplaceTest.java index 466124222d..67f05678a7 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/ReplaceTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/ReplaceTest.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. @@ -33,7 +33,7 @@ void fromContent() throws Exception { } private void runTest(String sourceContent, String targetContent) throws Exception { - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toContent(sourceContent); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).hasContent(targetContent); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/TrimTrailingWhitespaceTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/TrimTrailingWhitespaceTest.java index 8cb99f5c45..a0e020eaee 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/TrimTrailingWhitespaceTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/TrimTrailingWhitespaceTest.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,13 +26,13 @@ void fromContentToTabs() throws Exception { writePomWithFormatSteps( ""); - String target = "This line ends with whitespaces"; - String source = target + " "; + var target = "This line ends with whitespaces"; + var source = target + " "; runTest(source, target); } private void runTest(String sourceContent, String targetContent) throws Exception { - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toContent(sourceContent); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).hasContent(targetContent); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/groovy/GrEclipseTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/groovy/GrEclipseTest.java index 34d95dc7d2..5e9c3df11c 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/groovy/GrEclipseTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/groovy/GrEclipseTest.java @@ -27,7 +27,7 @@ class GrEclipseTest extends MavenIntegrationHarness { void testEclipse() throws Exception { writePomWithGrEclipse(); - String path = "src/main/groovy/test.groovy"; + var path = "src/main/groovy/test.groovy"; setFile(path).toResource("groovy/greclipse/format/unformatted.test"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("groovy/greclipse/format/formatted.test"); @@ -37,13 +37,13 @@ void testEclipse() throws Exception { void doesNotFormatJavaFiles() throws Exception { writePomWithGrEclipse(); - String javaPath = "src/main/java/test.java"; - String testJavaPath = "src/test/java/test.java"; + var javaPath = "src/main/java/test.java"; + var testJavaPath = "src/test/java/test.java"; setFile(javaPath).toResource("java/googlejavaformat/JavaCodeUnformatted.test"); setFile(testJavaPath).toResource("java/googlejavaformat/JavaCodeUnformatted.test"); - String groovyPath = "src/main/groovy/test.groovy"; - String testGroovyPath = "src/test/groovy/test.groovy"; + var groovyPath = "src/main/groovy/test.groovy"; + var testGroovyPath = "src/test/groovy/test.groovy"; setFile(groovyPath).toResource("groovy/greclipse/format/unformatted.test"); setFile(testGroovyPath).toResource("groovy/greclipse/format/unformatted.test"); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/groovy/ImportOrderTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/groovy/ImportOrderTest.java index 5cdca40d4c..ec5f35a449 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/groovy/ImportOrderTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/groovy/ImportOrderTest.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. @@ -50,7 +50,7 @@ private void runTest() throws Exception { } private void runTest(String expectedResource) throws Exception { - String path = "src/main/groovy/test.groovy"; + var path = "src/main/groovy/test.groovy"; setFile(path).toResource("java/importsorter/GroovyCodeUnsortedMisplacedImports.test"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource(expectedResource); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexHarness.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexHarness.java index 8260038efa..d83162f3b0 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexHarness.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexHarness.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. @@ -44,11 +44,11 @@ abstract class FileIndexHarness { void beforeEach(@TempDir Path tempDir) throws Exception { this.tempDir = tempDir; - Path projectDir = tempDir.resolve("my-project"); + var projectDir = tempDir.resolve("my-project"); Files.createDirectory(projectDir); when(config.getProjectDir()).thenReturn(projectDir); - Path indexFile = projectDir.resolve("target").resolve("spotless-index"); + var indexFile = projectDir.resolve("target").resolve("spotless-index"); when(config.getIndexFile()).thenReturn(indexFile); when(config.getPluginFingerprint()).thenReturn(FINGERPRINT); @@ -60,7 +60,7 @@ protected List createSourceFilesAndWriteIndexFile(PluginFingerprint finger List sourceFiles = new ArrayList<>(); for (String file : files) { - Path path = createSourceFile(file); + var path = createSourceFile(file); lines.add(file + " " + Files.getLastModifiedTime(path).toInstant()); sourceFiles.add(path); } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexTest.java index 8cd5e8a2f7..875e241c2d 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexTest.java @@ -143,8 +143,8 @@ void writeIndexContainingUpdates() throws Exception { createSourceFilesAndWriteIndexFile(FINGERPRINT, "source1.txt", "source2.txt"); Path sourceFile3 = createSourceFile("source3.txt"); Path sourceFile4 = createSourceFile("source4.txt"); - Instant modifiedTime3 = Instant.now(); - Instant modifiedTime4 = Instant.now().plusSeconds(42); + var modifiedTime3 = Instant.now(); + var modifiedTime4 = Instant.now().plusSeconds(42); FileIndex index1 = FileIndex.read(config, log); index1.setLastModifiedTime(sourceFile3, modifiedTime3); @@ -161,7 +161,7 @@ void writeIndexWhenParentDirDoesNotExist() throws Exception { assertThat(config.getIndexFile().getParent()).doesNotExist(); FileIndex index1 = FileIndex.read(config, log); Path sourceFile = createSourceFile("source.txt"); - Instant modifiedTime = Instant.now(); + var modifiedTime = Instant.now(); index1.setLastModifiedTime(sourceFile, modifiedTime); index1.write(); @@ -194,7 +194,7 @@ void getLastModifiedTimeReturnsEmptyOptionalForNonProjectFile() throws Exception createSourceFilesAndWriteIndexFile(FINGERPRINT, "source.txt"); Path nonProjectDir = tempDir.resolve("some-other-project"); Files.createDirectory(nonProjectDir); - Path nonProjectFile = Files.createFile(nonProjectDir.resolve("some-other-source.txt")); + var nonProjectFile = Files.createFile(nonProjectDir.resolve("some-other-source.txt")); FileIndex index = FileIndex.read(config, log); @@ -214,7 +214,7 @@ void getLastModifiedTimeReturnsEmptyOptionalForUnknownFile() throws Exception { @Test void setLastModifiedTimeThrowsForNonProjectFile() { FileIndex index = FileIndex.read(config, log); - Path nonProjectFile = Paths.get("non-project-file"); + var nonProjectFile = Paths.get("non-project-file"); assertThatThrownBy(() -> index.setLastModifiedTime(nonProjectFile, Instant.now())).isInstanceOf(IllegalArgumentException.class); } @@ -227,7 +227,7 @@ void setLastModifiedTimeUpdatesModifiedTime() throws Exception { Instant oldTime = index.getLastModifiedTime(sourceFile); assertThat(oldTime).isNotNull(); - Instant newTime = Instant.now().plusSeconds(42); + var newTime = Instant.now().plusSeconds(42); assertThat(oldTime).isNotEqualTo(newTime); index.setLastModifiedTime(sourceFile, newTime); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/IndexBasedCheckerTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/IndexBasedCheckerTest.java index 7137a32e1e..2c28eb454d 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/IndexBasedCheckerTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/IndexBasedCheckerTest.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. @@ -19,7 +19,6 @@ import java.nio.file.Files; import java.nio.file.Path; -import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -44,7 +43,7 @@ void isUpToDateReturnsFalseForUnknownFile() throws Exception { @Test void isUpToDateReturnsTrueWhenOnDiskFileIsSameAsInTheIndex() throws Exception { Path sourceFile = createSourceFile("source.txt"); - Instant modifiedTime = Files.getLastModifiedTime(sourceFile).toInstant(); + var modifiedTime = Files.getLastModifiedTime(sourceFile).toInstant(); index.setLastModifiedTime(sourceFile, modifiedTime); assertThat(checker.isUpToDate(sourceFile)).isTrue(); @@ -53,7 +52,7 @@ void isUpToDateReturnsTrueWhenOnDiskFileIsSameAsInTheIndex() throws Exception { @Test void isUpToDateReturnsFalseWhenOnDiskFileIsNewerThanInTheIndex() throws Exception { Path sourceFile = createSourceFile("source.txt"); - Instant modifiedTime = Files.getLastModifiedTime(sourceFile).toInstant().minusSeconds(42); + var modifiedTime = Files.getLastModifiedTime(sourceFile).toInstant().minusSeconds(42); index.setLastModifiedTime(sourceFile, modifiedTime); assertThat(checker.isUpToDate(sourceFile)).isFalse(); @@ -67,7 +66,7 @@ void isUpToDateReturnsFalseWhenOnDiskFileIsNewerThanInTheIndex() throws Exceptio @Test void isUpToDateReturnsFalseWhenOnDiskFileIsOlderThanInTheIndex() throws Exception { Path sourceFile = createSourceFile("source.txt"); - Instant modifiedTime = Files.getLastModifiedTime(sourceFile).toInstant().plusSeconds(42); + var modifiedTime = Files.getLastModifiedTime(sourceFile).toInstant().plusSeconds(42); index.setLastModifiedTime(sourceFile, modifiedTime); assertThat(checker.isUpToDate(sourceFile)).isFalse(); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/NoopCheckerTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/NoopCheckerTest.java index 404b5e2191..7c85069665 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/NoopCheckerTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/NoopCheckerTest.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. @@ -96,8 +96,8 @@ void neverUpToDate() { private MavenProject buildMavenProject() throws IOException { File projectDir = newFolder("project"); - File targetDir = new File(projectDir, "target"); - File pomFile = new File(projectDir, "pom.xml"); + var targetDir = new File(projectDir, "target"); + var pomFile = new File(projectDir, "pom.xml"); assertThat(targetDir.mkdir()).isTrue(); assertThat(pomFile.createNewFile()).isTrue(); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/PluginFingerprintTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/PluginFingerprintTest.java index ae61dec331..e2e9f742e7 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/PluginFingerprintTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/PluginFingerprintTest.java @@ -154,7 +154,7 @@ private MavenProject mavenProject(String spotlessVersion) throws Exception { } private static Model readPom(String xml) throws Exception { - byte[] bytes = xml.getBytes(UTF_8); + var bytes = xml.getBytes(UTF_8); try (XmlStreamReader xmlReader = ReaderFactory.newXmlReader(new ByteArrayInputStream(bytes))) { MavenXpp3Reader pomReader = new MavenXpp3Reader(); return pomReader.read(xmlReader); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/UpToDateCheckingTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/UpToDateCheckingTest.java index cfc17594ca..f3e93d37d4 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/UpToDateCheckingTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/UpToDateCheckingTest.java @@ -41,7 +41,7 @@ void upToDateCheckingEnabledByDefault() throws Exception { ""); List files = writeUnformattedFiles(1); - String output = runSpotlessApply(); + var output = runSpotlessApply(); assertThat(output).doesNotContain(DISABLED_MESSAGE); assertFormatted(files); @@ -52,7 +52,7 @@ void explicitlyEnableUpToDateChecking() throws Exception { writePomWithUpToDateCheckingEnabled(true); List files = writeUnformattedFiles(1); - String output = runSpotlessApply(); + var output = runSpotlessApply(); assertThat(output).doesNotContain(DISABLED_MESSAGE); assertFormatted(files); @@ -63,7 +63,7 @@ void explicitlyDisableUpToDateChecking() throws Exception { writePomWithUpToDateCheckingEnabled(false); List files = writeUnformattedFiles(1); - String output = runSpotlessApply(); + var output = runSpotlessApply(); assertThat(output).contains(DISABLED_MESSAGE); assertFormatted(files); @@ -74,7 +74,7 @@ void enableUpToDateCheckingWithPluginDependencies() throws Exception { writePomWithPluginManagementAndDependency(); List files = writeUnformattedFiles(1); - String output = runSpotlessApply(); + var output = runSpotlessApply(); assertThat(output).doesNotContain(DISABLED_MESSAGE); assertFormatted(files); @@ -87,7 +87,7 @@ void enableUpToDateCheckingWithPluginDependenciesMaven3_6_3() throws Exception { setFile(".mvn/wrapper/maven-wrapper.properties").toContent("distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip\n"); List files = writeUnformattedFiles(1); - String output = runSpotlessApply(); + var output = runSpotlessApply(); assertThat(output).doesNotContain(DISABLED_MESSAGE); assertFormatted(files); @@ -96,13 +96,13 @@ void enableUpToDateCheckingWithPluginDependenciesMaven3_6_3() throws Exception { @Test void enableUpToDateCheckingCustomIndexFile() throws Exception { Path tempDirectory = newFolder("index-files").toPath(); - Path indexFile = tempDirectory.resolve("com.diffplug.spotless/spotless-maven-plugin-tests.index"); + var indexFile = tempDirectory.resolve("com.diffplug.spotless/spotless-maven-plugin-tests.index"); assertThat(indexFile.getParent()).doesNotExist(); assertThat(indexFile).doesNotExist(); writePomWithUpToDateCheckingEnabledIndexFile(true, tempDirectory + "/${project.groupId}/${project.artifactId}.index"); List files = writeUnformattedFiles(1); - String output = runSpotlessApply(); + var output = runSpotlessApply(); assertThat(output).doesNotContain(DISABLED_MESSAGE); assertFormatted(files); @@ -113,7 +113,7 @@ void enableUpToDateCheckingCustomIndexFile() throws Exception { @Test void disableUpToDateCheckingCustomIndexFile() throws Exception { Path tempDirectory = newFolder("index-files").toPath(); - Path indexFile = tempDirectory.resolve("com.diffplug.spotless/spotless-maven-plugin-tests.index"); + var indexFile = tempDirectory.resolve("com.diffplug.spotless/spotless-maven-plugin-tests.index"); Files.createDirectories(indexFile.getParent()); Files.createFile(indexFile); assertThat(indexFile.getParent()).exists(); @@ -121,7 +121,7 @@ void disableUpToDateCheckingCustomIndexFile() throws Exception { writePomWithUpToDateCheckingEnabledIndexFile(false, tempDirectory + "/${project.groupId}/${project.artifactId}.index"); List files = writeUnformattedFiles(1); - String output = runSpotlessApply(); + var output = runSpotlessApply(); assertThat(output).contains(DISABLED_MESSAGE); assertFormatted(files); @@ -134,14 +134,14 @@ void spotlessApplyRecordsCorrectlyFormattedFiles() throws Exception { writePomWithUpToDateCheckingEnabled(true); List files = writeFormattedFiles(5); - String applyOutput1 = runSpotlessApply(); + var applyOutput1 = runSpotlessApply(); assertSpotlessApplyDidNotSkipAnyFiles(applyOutput1); assertFormatted(files); - String applyOutput2 = runSpotlessApply(); + var applyOutput2 = runSpotlessApply(); assertSpotlessApplySkipped(files, applyOutput2); - String checkOutput = runSpotlessCheck(); + var checkOutput = runSpotlessCheck(); assertSpotlessCheckSkipped(files, checkOutput); } @@ -150,14 +150,14 @@ void spotlessApplyRecordsUnformattedFiles() throws Exception { writePomWithUpToDateCheckingEnabled(true); List files = writeUnformattedFiles(4); - String applyOutput1 = runSpotlessApply(); + var applyOutput1 = runSpotlessApply(); assertSpotlessApplyDidNotSkipAnyFiles(applyOutput1); assertFormatted(files); - String applyOutput2 = runSpotlessApply(); + var applyOutput2 = runSpotlessApply(); assertSpotlessApplySkipped(files, applyOutput2); - String checkOutput = runSpotlessCheck(); + var checkOutput = runSpotlessCheck(); assertSpotlessCheckSkipped(files, checkOutput); } @@ -166,13 +166,13 @@ void spotlessCheckRecordsCorrectlyFormattedFiles() throws Exception { writePomWithUpToDateCheckingEnabled(true); List files = writeFormattedFiles(7); - String checkOutput1 = runSpotlessCheck(); + var checkOutput1 = runSpotlessCheck(); assertSpotlessCheckDidNotSkipAnyFiles(checkOutput1); - String checkOutput2 = runSpotlessCheck(); + var checkOutput2 = runSpotlessCheck(); assertSpotlessCheckSkipped(files, checkOutput2); - String applyOutput = runSpotlessApply(); + var applyOutput = runSpotlessApply(); assertSpotlessApplySkipped(files, applyOutput); } @@ -181,17 +181,17 @@ void spotlessCheckRecordsUnformattedFiles() throws Exception { writePomWithUpToDateCheckingEnabled(true); List files = writeUnformattedFiles(6); - String checkOutput1 = runSpotlessCheckOnUnformattedFiles(); + var checkOutput1 = runSpotlessCheckOnUnformattedFiles(); assertSpotlessCheckDidNotSkipAnyFiles(checkOutput1); - String checkOutput2 = runSpotlessCheckOnUnformattedFiles(); + var checkOutput2 = runSpotlessCheckOnUnformattedFiles(); assertSpotlessCheckDidNotSkipAnyFiles(checkOutput2); - String applyOutput = runSpotlessApply(); + var applyOutput = runSpotlessApply(); assertSpotlessApplyDidNotSkipAnyFiles(applyOutput); assertFormatted(files); - String checkOutput3 = runSpotlessCheck(); + var checkOutput3 = runSpotlessCheck(); assertSpotlessCheckSkipped(files, checkOutput3); } @@ -245,8 +245,8 @@ private List writeUnformattedFiles(int count) throws IOException { private List writeFiles(String resource, String suffix, int count) throws IOException { List result = new ArrayList<>(count); - for (int i = 0; i < count; i++) { - String path = "src/main/java/test_" + suffix + "_" + i + ".java"; + for (var i = 0; i < count; i++) { + var path = "src/main/java/test_" + suffix + "_" + i + ".java"; File file = setFile(path).toResource(resource); result.add(file); } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java index 738624cd57..e87b11a5ca 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java @@ -105,7 +105,7 @@ void testIncludeOnlyLiteralsFirstInComparisons() throws Exception { } private void runTest(String dirtyPath, String cleanPath) throws Exception { - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toResource("java/cleanthat/" + dirtyPath); // .withRemoteDebug(21654) Assertions.assertThat(mavenRunner().withArguments("spotless:apply").runNoError().stdOutUtf8()).doesNotContain("[ERROR]"); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/EclipseFormatStepTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/EclipseFormatStepTest.java index 792a2a1382..418f7ecd3c 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/EclipseFormatStepTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/EclipseFormatStepTest.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. @@ -29,7 +29,7 @@ void testEclipse() throws Exception { ""); setFile("formatter.xml").toResource("java/eclipse/formatter.xml"); - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toResource("java/eclipse/JavaCodeUnformatted.test"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("java/eclipse/JavaCodeFormatted.test"); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/FormatAnnotationsStepTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/FormatAnnotationsStepTest.java index 972a4b4f7f..cd9105cb66 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/FormatAnnotationsStepTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/FormatAnnotationsStepTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2022 DiffPlug + * Copyright 2022-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ class FormatAnnotationsStepTest extends MavenIntegrationHarness { void testFormatAnnotations() throws Exception { writePomWithJavaSteps(""); - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toResource("java/formatannotations/FormatAnnotationsTestInput.test"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("java/formatannotations/FormatAnnotationsTestOutput.test"); @@ -35,7 +35,7 @@ void testFormatAnnotations() throws Exception { void testFormatAnnotationsAccessModifiers() throws Exception { writePomWithJavaSteps(""); - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toResource("java/formatannotations/FormatAnnotationsAccessModifiersInput.test"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("java/formatannotations/FormatAnnotationsAccessModifiersOutput.test"); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/GoogleJavaFormatTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/GoogleJavaFormatTest.java index 407d089999..cf90fbd938 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/GoogleJavaFormatTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/GoogleJavaFormatTest.java @@ -53,7 +53,7 @@ void specificVersionReflowLongStrings() throws Exception { } private void runTest(String targetResource) throws Exception { - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toResource("java/googlejavaformat/JavaCodeUnformatted.test"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource(targetResource); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/ImportOrderTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/ImportOrderTest.java index 2eef48083e..cd3b46777c 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/ImportOrderTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/ImportOrderTest.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. @@ -59,7 +59,7 @@ private void runTest() throws Exception { } private void runTest(String expectedResource) throws Exception { - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toResource("java/importsorter/JavaCodeUnsortedImports.test"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource(expectedResource); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/PalantirJavaFormatTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/PalantirJavaFormatTest.java index d8d66fa46d..6fc9786472 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/PalantirJavaFormatTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/PalantirJavaFormatTest.java @@ -41,7 +41,7 @@ void specificJava11Version2() throws Exception { } private void runTest(String targetResource) throws Exception { - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toResource("java/palantirjavaformat/JavaCodeUnformatted.test"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource(targetResource); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/RemoveUnusedImportsStepTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/RemoveUnusedImportsStepTest.java index 50853ba914..3466f467d0 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/RemoveUnusedImportsStepTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/RemoveUnusedImportsStepTest.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. @@ -25,7 +25,7 @@ class RemoveUnusedImportsStepTest extends MavenIntegrationHarness { void testRemoveUnusedInports() throws Exception { writePomWithJavaSteps(""); - String path = "src/main/java/test.java"; + var path = "src/main/java/test.java"; setFile(path).toResource("java/removeunusedimports/JavaCodeWithPackageUnformatted.test"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("java/removeunusedimports/JavaCodeWithPackageFormatted.test"); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/javascript/JavascriptFormatStepTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/javascript/JavascriptFormatStepTest.java index d738e17dac..9c1f2f9d2b 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/javascript/JavascriptFormatStepTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/javascript/JavascriptFormatStepTest.java @@ -78,7 +78,7 @@ class EslintStyleguidesTest extends MavenIntegrationHarness { @ParameterizedTest(name = "{index}: eslint js formatting with configFile using styleguide {0}") @ValueSource(strings = {"airbnb", "google", "standard", "xo"}) void eslintJsStyleguideUsingConfigFile(String styleGuide) throws Exception { - final String styleGuidePath = "npm/eslint/javascript/styleguide/" + styleGuide; + final var styleGuidePath = "npm/eslint/javascript/styleguide/" + styleGuide; writePomWithJavascriptSteps( TEST_FILE_PATH, @@ -96,7 +96,7 @@ void eslintJsStyleguideUsingConfigFile(String styleGuide) throws Exception { @ParameterizedTest(name = "{index}: eslint js formatting with inline config using styleguide {0}") @ValueSource(strings = {"airbnb", "google", "standard", "xo"}) void eslintJsStyleguideUsingInlineConfig(String styleGuide) throws Exception { - final String styleGuidePath = "npm/eslint/javascript/styleguide/" + styleGuide; + final var styleGuidePath = "npm/eslint/javascript/styleguide/" + styleGuide; final String escapedInlineConfig = ResourceHarness.getTestResource(styleGuidePath + "/.eslintrc.js") .replace("<", "<") @@ -115,7 +115,7 @@ void eslintJsStyleguideUsingInlineConfig(String styleGuide) throws Exception { @Test void provideCustomDependenciesForStyleguideStandard() throws Exception { - final String styleGuidePath = "npm/eslint/javascript/styleguide/standard"; + final var styleGuidePath = "npm/eslint/javascript/styleguide/standard"; writePomWithJavascriptSteps( TEST_FILE_PATH, diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/DiktatTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/DiktatTest.java index dc6e59fef0..97d5f9552a 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/DiktatTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/DiktatTest.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. @@ -28,7 +28,7 @@ void testDiktat() throws Exception { writePomWithKotlinSteps(""); - String path = "src/main/kotlin/Main.kt"; + var path = "src/main/kotlin/Main.kt"; setFile(path).toResource("kotlin/diktat/main.dirty"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("kotlin/diktat/main.clean"); @@ -43,7 +43,7 @@ void testDiktatWithVersion() throws Exception { " 1.2.1", ""); - String path = "src/main/kotlin/Main.kt"; + var path = "src/main/kotlin/Main.kt"; setFile(path).toResource("kotlin/diktat/main.dirty"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("kotlin/diktat/main.clean"); @@ -52,7 +52,7 @@ void testDiktatWithVersion() throws Exception { @Test void testDiktatConfig() throws Exception { - String configPath = "src/main/kotlin/diktat-analysis.yml"; + var configPath = "src/main/kotlin/diktat-analysis.yml"; File conf = setFile(configPath).toResource("kotlin/diktat/diktat-analysis.yml"); writePomWithKotlinSteps( "", @@ -60,7 +60,7 @@ void testDiktatConfig() throws Exception { " " + conf.getAbsolutePath() + "", ""); - String path = "src/main/kotlin/Main.kt"; + var path = "src/main/kotlin/Main.kt"; setFile(path).toResource("kotlin/diktat/main.dirty"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("kotlin/diktat/main.clean"); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtfmtTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtfmtTest.java index e452c5d56b..0441e691e5 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtfmtTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtfmtTest.java @@ -24,8 +24,8 @@ class KtfmtTest extends MavenIntegrationHarness { void testKtfmt() throws Exception { writePomWithKotlinSteps(""); - String path1 = "src/main/kotlin/main1.kt"; - String path2 = "src/main/kotlin/main2.kt"; + var path1 = "src/main/kotlin/main1.kt"; + var path2 = "src/main/kotlin/main2.kt"; setFile(path1).toResource("kotlin/ktfmt/basic.dirty"); setFile(path2).toResource("kotlin/ktfmt/basic.dirty"); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtlintTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtlintTest.java index ba6f1d8e2c..17b0f5a922 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtlintTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtlintTest.java @@ -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. @@ -24,7 +24,7 @@ class KtlintTest extends MavenIntegrationHarness { void testKtlint() throws Exception { writePomWithKotlinSteps(""); - String path = "src/main/kotlin/Main.kt"; + var path = "src/main/kotlin/Main.kt"; setFile(path).toResource("kotlin/ktlint/basic.dirty"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("kotlin/ktlint/basic.clean"); @@ -34,7 +34,7 @@ void testKtlint() throws Exception { void testKtlintEditorConfigOverride() throws Exception { writePomWithKotlinSteps("truetrue"); - String path = "src/main/kotlin/Main.kt"; + var path = "src/main/kotlin/Main.kt"; setFile(path).toResource("kotlin/ktlint/experimentalEditorConfigOverride.dirty"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("kotlin/ktlint/experimentalEditorConfigOverride.clean"); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmStepsWithNpmInstallCacheTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmStepsWithNpmInstallCacheTest.java index aae587aadb..979449ff95 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmStepsWithNpmInstallCacheTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmStepsWithNpmInstallCacheTest.java @@ -41,7 +41,7 @@ public class NpmStepsWithNpmInstallCacheTest extends MavenIntegrationHarness { @Test void prettierTypescriptWithoutCache() throws Exception { - String suffix = "ts"; + var suffix = "ts"; writePomWithPrettierSteps("**/*." + suffix, "", " 1.16.4", @@ -53,7 +53,7 @@ void prettierTypescriptWithoutCache() throws Exception { @Test void prettierTypescriptWithDefaultCache() throws Exception { - String suffix = "ts"; + var suffix = "ts"; writePomWithPrettierSteps("**/*." + suffix, "", " 1.16.4", @@ -69,7 +69,7 @@ void prettierTypescriptWithDefaultCache() throws Exception { @Test void prettierTypescriptWithDefaultCacheIsReusedOnSecondRun() throws Exception { - String suffix = "ts"; + var suffix = "ts"; writePomWithPrettierSteps("**/*." + suffix, "", " 1.16.4", @@ -94,7 +94,7 @@ void prettierTypescriptWithDefaultCacheIsReusedOnSecondRun() throws Exception { @Test void prettierTypescriptWithSpecificCache() throws Exception { - String suffix = "ts"; + var suffix = "ts"; File cacheDir = newFolder("cache-prettier-1"); writePomWithPrettierSteps("**/*." + suffix, "", @@ -111,7 +111,7 @@ void prettierTypescriptWithSpecificCache() throws Exception { @Test void prettierTypescriptWithSpecificCacheIsUsedOnSecondRun() throws Exception { - String suffix = "ts"; + var suffix = "ts"; File cacheDir = newFolder("cache-prettier-1"); writePomWithPrettierSteps("**/*." + suffix, "", @@ -140,16 +140,16 @@ private void recursiveDelete(Path path, String exclusion) throws IOException { } private Result run(String kind, String suffix) throws IOException, InterruptedException { - String path = prepareRun(kind, suffix); + var path = prepareRun(kind, suffix); Result result = mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("npm/prettier/filetypes/" + kind + "/" + kind + ".clean"); return result; } private String prepareRun(String kind, String suffix) throws IOException { - String configPath = ".prettierrc.yml"; + var configPath = ".prettierrc.yml"; setFile(configPath).toResource("npm/prettier/filetypes/" + kind + "/" + ".prettierrc.yml"); - String path = "src/main/" + kind + "/test." + suffix; + var path = "src/main/" + kind + "/test." + suffix; setFile(path).toResource("npm/prettier/filetypes/" + kind + "/" + kind + ".dirty"); return path; } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmTestsWithDynamicallyInstalledNpmInstallationTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmTestsWithDynamicallyInstalledNpmInstallationTest.java index 78830bf09d..6aeb6cc8c5 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmTestsWithDynamicallyInstalledNpmInstallationTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/npm/NpmTestsWithDynamicallyInstalledNpmInstallationTest.java @@ -34,11 +34,11 @@ void useDownloadedNpmInstallation() throws Exception { " " + installedNpmPath() + "", ""); - String kind = "typescript"; - String suffix = "ts"; - String configPath = ".prettierrc.yml"; + var kind = "typescript"; + var suffix = "ts"; + var configPath = ".prettierrc.yml"; setFile(configPath).toResource("npm/prettier/filetypes/" + kind + "/" + ".prettierrc.yml"); - String path = "src/main/" + kind + "/test." + suffix; + var path = "src/main/" + kind + "/test." + suffix; setFile(path).toResource("npm/prettier/filetypes/" + kind + "/" + kind + ".dirty"); mavenRunner().withArguments(installNpmMavenGoal(), "spotless:apply").runNoError(); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/prettier/PrettierFormatStepTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/prettier/PrettierFormatStepTest.java index 78a0fc30ff..2f115b0243 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/prettier/PrettierFormatStepTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/prettier/PrettierFormatStepTest.java @@ -30,27 +30,27 @@ class PrettierFormatStepTest extends MavenIntegrationHarness { private void run(String kind, String suffix) throws IOException, InterruptedException { - String path = prepareRun(kind, suffix); + var path = prepareRun(kind, suffix); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("npm/prettier/filetypes/" + kind + "/" + kind + ".clean"); } private String prepareRun(String kind, String suffix) throws IOException { - String configPath = ".prettierrc.yml"; + var configPath = ".prettierrc.yml"; setFile(configPath).toResource("npm/prettier/filetypes/" + kind + "/" + ".prettierrc.yml"); - String path = "src/main/" + kind + "/test." + suffix; + var path = "src/main/" + kind + "/test." + suffix; setFile(path).toResource("npm/prettier/filetypes/" + kind + "/" + kind + ".dirty"); return path; } private ProcessRunner.Result runExpectingError(String kind, String suffix) throws IOException, InterruptedException { - String path = prepareRun(kind, suffix); + var path = prepareRun(kind, suffix); return mavenRunner().withArguments("spotless:apply").runHasError(); } @Test void prettier_typescript() throws Exception { - String suffix = "ts"; + var suffix = "ts"; writePomWithPrettierSteps("**/*." + suffix, "", " 1.16.4", @@ -61,7 +61,7 @@ void prettier_typescript() throws Exception { @Test void prettier_html() throws Exception { - String suffix = "html"; + var suffix = "html"; writePomWithPrettierSteps("**/*." + suffix, "", " 1.16.4", @@ -72,7 +72,7 @@ void prettier_html() throws Exception { @Test void prettier_tsx() throws Exception { - String suffix = "tsx"; + var suffix = "tsx"; writePomWithPrettierSteps("src/main/**/*." + suffix, "src/**/*.tsx", "", @@ -84,7 +84,7 @@ void prettier_tsx() throws Exception { @Test void prettier_tsx_inline_config() throws Exception { - String suffix = "tsx"; + var suffix = "tsx"; writePomWithPrettierSteps("src/main/**/*." + suffix, "", " 1.16.4", @@ -202,7 +202,7 @@ void autodetect_npmrc_file() throws Exception { "fetch-timeout=250", "fetch-retry-mintimeout=250", "fetch-retry-maxtimeout=250"); - String suffix = "ts"; + var suffix = "ts"; writePomWithPrettierSteps("**/*." + suffix, "", " 1.16.4", @@ -219,7 +219,7 @@ void select_configured_npmrc_file() throws Exception { "fetch-timeout=250", "fetch-retry-mintimeout=250", "fetch-retry-maxtimeout=250"); - String suffix = "ts"; + var suffix = "ts"; writePomWithPrettierSteps("**/*." + suffix, "", " 1.16.4", diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/scala/ScalafmtTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/scala/ScalafmtTest.java index ef36c29d8b..2206417c46 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/scala/ScalafmtTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/scala/ScalafmtTest.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,7 +40,7 @@ void testScalafmtWithCustomConfig() throws Exception { } private void runTest(String s) throws Exception { - String path = "src/main/scala/test.scala"; + var path = "src/main/scala/test.scala"; setFile(path).toResource("scala/scalafmt/basic.dirty"); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource(s); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/typescript/TypescriptFormatStepTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/typescript/TypescriptFormatStepTest.java index a09111d30d..f294d03184 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/typescript/TypescriptFormatStepTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/typescript/TypescriptFormatStepTest.java @@ -38,7 +38,7 @@ private static String styleGuideDevDependenciesString(String styleGuideName) { } private void runTsfmt(String kind) throws IOException, InterruptedException { - String path = prepareRunTsfmt(kind); + var path = prepareRunTsfmt(kind); mavenRunner().withArguments("spotless:apply").runNoError(); assertFile(path).sameAsResource("npm/tsfmt/" + kind + "/" + kind + ".clean"); } @@ -112,7 +112,7 @@ void tsconfig() throws Exception { @Test void testTypescript_2_Configs() throws Exception { - String path = "src/main/typescript/test.ts"; + var path = "src/main/typescript/test.ts"; writePomWithTypescriptSteps( path, diff --git a/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java b/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java index 4d0a340f42..acf9c049b7 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. @@ -41,7 +41,7 @@ public static void dumpMethod(Method method) { System.out.print(" " + method.getName() + "("); Iterator paramIter = Arrays.asList(method.getParameters()).iterator(); while (paramIter.hasNext()) { - Parameter param = paramIter.next(); + var param = paramIter.next(); System.out.print(param.getType().getName()); if (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..08159e825a 100644 --- a/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java +++ b/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java @@ -61,7 +61,7 @@ protected File newFile(String subpath) { /** Creates and returns a new child-folder of the root folder. */ protected File newFolder(String subpath) throws IOException { - File targetDir = newFile(subpath); + var targetDir = newFile(subpath); if (!targetDir.mkdir()) { throw new IOException("Failed to create " + targetDir); } @@ -77,8 +77,8 @@ protected String read(Path path, Charset encoding) throws IOException { } protected void replace(String path, String toReplace, String replaceWith) throws IOException { - String before = read(path); - String after = before.replace(toReplace, replaceWith); + var before = read(path); + var after = before.replace(toReplace, replaceWith); if (before.equals(after)) { throw new IllegalArgumentException("Replace was ineffective! '" + toReplace + "' was not found in " + path); } @@ -99,7 +99,7 @@ protected static boolean existsTestResource(String filename) { } private static Optional getTestResourceUrl(String filename) { - URL url = ResourceHarness.class.getResource("/" + filename); + var url = ResourceHarness.class.getResource("/" + filename); return Optional.ofNullable(url); } @@ -122,9 +122,9 @@ protected File createTestFile(String filename) { * src/test/resources directory. */ protected File createTestFile(String filename, UnaryOperator fileContentsProcessor) { - int lastSlash = filename.lastIndexOf('/'); - String name = lastSlash >= 0 ? filename.substring(lastSlash) : filename; - File file = newFile(name); + var lastSlash = filename.lastIndexOf('/'); + var name = lastSlash >= 0 ? filename.substring(lastSlash) : filename; + var file = newFile(name); file.getParentFile().mkdirs(); ThrowingEx.run(() -> Files.write(file.toPath(), fileContentsProcessor.apply(getTestResource(filename)).getBytes(StandardCharsets.UTF_8))); return file; @@ -164,7 +164,7 @@ public void sameAsResource(String resource) throws IOException { } public void matches(Consumer> conditions) throws IOException { - String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + var content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); conditions.accept(assertThat(content)); } } diff --git a/testlib/src/main/java/com/diffplug/spotless/SerializableEqualityTester.java b/testlib/src/main/java/com/diffplug/spotless/SerializableEqualityTester.java index 096edf62e2..034200b400 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,7 +37,7 @@ public interface API { public void testEquals() { List> allGroups = new ArrayList<>(); Box> currentGroup = Box.of(new ArrayList<>()); - API api = new API() { + var api = new API() { @Override public void areDifferentThan() { currentGroup.modify(current -> { @@ -73,8 +73,8 @@ public void areDifferentThan() { @SuppressWarnings("unchecked") private static T reserialize(T input) { byte[] asBytes = LazyForwardingEquality.toBytes(input); - ByteArrayInputStream byteInput = new ByteArrayInputStream(asBytes); - try (ObjectInputStream objectInput = new ObjectInputStream(byteInput)) { + var byteInput = new ByteArrayInputStream(asBytes); + try (var objectInput = new ObjectInputStream(byteInput)) { return (T) objectInput.readObject(); } catch (IOException | ClassNotFoundException e) { throw ThrowingEx.asRuntime(e); diff --git a/testlib/src/main/java/com/diffplug/spotless/StepHarness.java b/testlib/src/main/java/com/diffplug/spotless/StepHarness.java index c611cc738a..81f5073518 100644 --- a/testlib/src/main/java/com/diffplug/spotless/StepHarness.java +++ b/testlib/src/main/java/com/diffplug/spotless/StepHarness.java @@ -94,7 +94,7 @@ public AbstractStringAssert testExceptionMsg(String before) { if (e instanceof SecurityException) { throw new AssertionError(e.getMessage()); } else { - Throwable rootCause = e; + var rootCause = e; while (rootCause.getCause() != null) { if (rootCause instanceof IllegalStateException) { break; diff --git a/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java b/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java index 9a9eb4042b..2aafe943ff 100644 --- a/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java +++ b/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java @@ -102,7 +102,7 @@ public AbstractStringAssert testExceptionMsg(File file, String before) { if (e instanceof SecurityException) { throw new AssertionError(e.getMessage()); } else { - Throwable rootCause = e; + var rootCause = e; while (rootCause.getCause() != null) { rootCause = rootCause.getCause(); } diff --git a/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java b/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java index 0d9ced4c9e..7fc0774696 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. @@ -42,7 +42,7 @@ public class TestProvisioner { public static Project gradleProject(File dir) { - File userHome = new File(StandardSystemProperty.USER_HOME.value()); + var userHome = new File(StandardSystemProperty.USER_HOME.value()); return ProjectBuilder.builder() .withGradleUserHomeDir(new File(userHome, ".gradle")) .withProjectDir(dir) @@ -94,13 +94,13 @@ private static Provisioner createWithRepositories(Consumer re /** Creates a Provisioner which will cache the result of previous calls. */ @SuppressWarnings("unchecked") private static Provisioner caching(String name, Supplier input) { - File spotlessDir = new File(StandardSystemProperty.USER_DIR.value()).getParentFile(); - File testlib = new File(spotlessDir, "testlib"); - File cacheFile = new File(testlib, "build/tmp/testprovisioner." + name + ".cache"); + var spotlessDir = new File(StandardSystemProperty.USER_DIR.value()).getParentFile(); + var testlib = new File(spotlessDir, "testlib"); + var cacheFile = new File(testlib, "build/tmp/testprovisioner." + name + ".cache"); Map, ImmutableSet> cached; if (cacheFile.exists()) { - try (ObjectInputStream inputStream = new ObjectInputStream(Files.asByteSource(cacheFile).openBufferedStream())) { + try (var inputStream = new ObjectInputStream(Files.asByteSource(cacheFile).openBufferedStream())) { cached = (Map, ImmutableSet>) inputStream.readObject(); } catch (IOException | ClassNotFoundException e) { throw Errors.asRuntime(e); @@ -118,11 +118,11 @@ private static Provisioner caching(String name, Supplier input) { synchronized (TestProvisioner.class) { ImmutableSet result = cached.get(mavenCoords); // double-check that depcache pruning hasn't removed them since our cache cached them - boolean needsToBeSet = result == null || !result.stream().allMatch(file -> file.exists() && file.isFile() && file.length() > 0); + var needsToBeSet = result == null || !result.stream().allMatch(file -> file.exists() && file.isFile() && file.length() > 0); if (needsToBeSet) { result = ImmutableSet.copyOf(input.get().provisionWithTransitives(withTransitives, mavenCoords)); cached.put(mavenCoords, result); - try (ObjectOutputStream outputStream = new ObjectOutputStream(Files.asByteSink(cacheFile).openBufferedStream())) { + try (var outputStream = new ObjectOutputStream(Files.asByteSink(cacheFile).openBufferedStream())) { outputStream.writeObject(cached); } catch (IOException e) { throw Errors.asRuntime(e); diff --git a/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java b/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java index d634119567..52da81f08e 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. @@ -46,8 +46,8 @@ void cp1252asUtf8() throws UnsupportedEncodingException { } private void cp1252asUtf8(String test, @Nullable String expectedMessage) throws UnsupportedEncodingException { - byte[] cp1252 = test.getBytes("cp1252"); - String asUTF = new String(cp1252, StandardCharsets.UTF_8); + var cp1252 = test.getBytes("cp1252"); + var asUTF = new String(cp1252, StandardCharsets.UTF_8); String actualMessage = EncodingErrorMsg.msg(asUTF, cp1252, StandardCharsets.UTF_8); Assertions.assertThat(actualMessage).isEqualTo(expectedMessage); } @@ -82,16 +82,16 @@ void utf8asCP1252() throws UnsupportedEncodingException { } private void utf8asCP1252(String test, @Nullable String expectedMessage) throws UnsupportedEncodingException { - byte[] utf8 = test.getBytes(StandardCharsets.UTF_8); - String asCp1252 = new String(utf8, "cp1252"); + var utf8 = test.getBytes(StandardCharsets.UTF_8); + var asCp1252 = new String(utf8, "cp1252"); String actualMessage = EncodingErrorMsg.msg(asCp1252, utf8, Charset.forName("cp1252")); Assertions.assertThat(actualMessage).isEqualTo(expectedMessage); } @Test void canUseUnrepresentableOnPurpose() throws UnsupportedEncodingException { - String pathologic = new String(new char[]{EncodingErrorMsg.UNREPRESENTABLE}); - byte[] pathologicBytes = pathologic.getBytes(StandardCharsets.UTF_8); + var pathologic = new String(new char[]{EncodingErrorMsg.UNREPRESENTABLE}); + var 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/FileSignatureTest.java b/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java index ab7c8c277b..60258f8d6a 100644 --- a/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.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. @@ -55,14 +55,14 @@ void testFromSet() throws IOException { @Test void testFromDirectory() { - File dir = new File(rootFolder(), "dir"); + var dir = new File(rootFolder(), "dir"); assertThatThrownBy(() -> FileSignature.signAsList(dir)) .isInstanceOf(IllegalArgumentException.class); } @Test void testFromFilesAndDirectory() throws IOException { - File dir = new File(rootFolder(), "dir"); + var dir = new File(rootFolder(), "dir"); List files = getTestFiles(inputPaths); files.add(dir); Collections.shuffle(files); diff --git a/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java b/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java index 5e47e9ad1a..4c1bf512c6 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. @@ -81,7 +81,7 @@ void multiplePropertyFiles() throws IOException { void invalidPropertyFiles() throws IOException { for (String settingsResource : INVALID_SETTINGS_RESOURCES) { File settingsFile = createTestFile(settingsResource); - boolean exceptionCaught = false; + var exceptionCaught = false; try { FormatterProperties.from(settingsFile); } catch (IllegalArgumentException ex) { @@ -124,16 +124,16 @@ public FormatterSettingsAssert containsSpecificValuesOf(Collection files) public FormatterSettingsAssert containsSpecificValuesOf(File file) { isNotNull(); - String fileName = file.getName(); + var fileName = file.getName(); Properties settingsProps = actual.getProperties(); for (String expectedValue : VALID_VALUES) { // A parsable (valid) file contains keys of the following format - String validValueName = (null == expectedValue) ? "null" : expectedValue; - String key = String.format("%s.%s", fileName, validValueName); + var validValueName = (null == expectedValue) ? "null" : expectedValue; + var key = String.format("%s.%s", fileName, validValueName); if (!settingsProps.containsKey(key)) { failWithMessage("Key <%s> not part of formatter settings.", key); } - String value = settingsProps.getProperty(key); + var value = settingsProps.getProperty(key); if ((null != expectedValue) && (!expectedValue.equals(value))) { failWithMessage("Value of key <%s> is '%s' and not '%s' as expected.", key, value, expectedValue); } @@ -144,13 +144,13 @@ public FormatterSettingsAssert containsSpecificValuesOf(File file) { public FormatterSettingsAssert containsCommonValueOf(final File file) { isNotNull(); - String fileName = file.getName(); + var fileName = file.getName(); Properties settingsProps = actual.getProperties(); - String key = "common"; + var key = "common"; if (!settingsProps.containsKey(key)) { failWithMessage("Key <%s> not part of formatter settings. Value '%s' had been expected.", key, fileName); } - String value = settingsProps.getProperty(key); + var value = settingsProps.getProperty(key); if (!fileName.equals(value)) { failWithMessage("Value of key <%s> is '%s' and not '%s' as expected.", key, value, fileName); } diff --git a/testlib/src/test/java/com/diffplug/spotless/FormatterTest.java b/testlib/src/test/java/com/diffplug/spotless/FormatterTest.java index 314507bd8d..b973394deb 100644 --- a/testlib/src/test/java/com/diffplug/spotless/FormatterTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/FormatterTest.java @@ -99,7 +99,7 @@ protected Formatter create() { @Test public void testExceptionWithEmptyPath() throws Exception { LineEnding.Policy lineEndingsPolicy = LineEnding.UNIX.createPolicy(); - Charset encoding = StandardCharsets.UTF_8; + var encoding = StandardCharsets.UTF_8; FormatExceptionPolicy exceptionPolicy = FormatExceptionPolicy.failOnlyOnError(); Path rootDir = Paths.get(StandardSystemProperty.USER_DIR.value()); @@ -124,7 +124,7 @@ public void testExceptionWithEmptyPath() throws Exception { @Test public void testExceptionWithSentinelNoFileOnDisk() throws Exception { LineEnding.Policy lineEndingsPolicy = LineEnding.UNIX.createPolicy(); - Charset encoding = StandardCharsets.UTF_8; + var encoding = StandardCharsets.UTF_8; FormatExceptionPolicy exceptionPolicy = FormatExceptionPolicy.failOnlyOnError(); Path rootDir = Paths.get(StandardSystemProperty.USER_DIR.value()); @@ -149,7 +149,7 @@ public void testExceptionWithSentinelNoFileOnDisk() throws Exception { @Test public void testExceptionWithRootDirIsNotFileSystem() throws Exception { LineEnding.Policy lineEndingsPolicy = LineEnding.UNIX.createPolicy(); - Charset encoding = StandardCharsets.UTF_8; + var encoding = StandardCharsets.UTF_8; FormatExceptionPolicy exceptionPolicy = FormatExceptionPolicy.failOnlyOnError(); Path rootDir = Mockito.mock(Path.class); diff --git a/testlib/src/test/java/com/diffplug/spotless/JvmTest.java b/testlib/src/test/java/com/diffplug/spotless/JvmTest.java index ca7fb71305..a7c257db99 100644 --- a/testlib/src/test/java/com/diffplug/spotless/JvmTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/JvmTest.java @@ -75,7 +75,7 @@ void supportEmptyConfiguration() { testSupport.assertFormatterSupported("0.1"); - Exception expected = new Exception("Some test exception"); + var expected = new Exception("Some test exception"); Exception actual = assertThrows(Exception.class, () -> { testSupport.suggestLaterVersionOnError("0.0", unused -> { throw expected; @@ -87,7 +87,7 @@ void supportEmptyConfiguration() { @Test void supportListsMinimumJvmIfOnlyHigherJvmSupported() { int higherJvmVersion = Jvm.version() + 1; - Exception testException = new Exception("Some test exception"); + var testException = new Exception("Some test exception"); testSupport.add(higherJvmVersion, "1.2.3"); testSupport.add(higherJvmVersion + 1, "2.2.3"); @@ -171,7 +171,7 @@ void supportAllowsExperimentalVersions() { for (String fmtVersion : Arrays.asList("1", "2.0")) { testSupport.assertFormatterSupported(fmtVersion); - Exception testException = new Exception("Some test exception"); + var testException = new Exception("Some test exception"); Exception exception = assertThrows(Exception.class, () -> { testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { throw testException; diff --git a/testlib/src/test/java/com/diffplug/spotless/PaddedCellTest.java b/testlib/src/test/java/com/diffplug/spotless/PaddedCellTest.java index dae41678a4..b37d0e4c5a 100644 --- a/testlib/src/test/java/com/diffplug/spotless/PaddedCellTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/PaddedCellTest.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. @@ -54,7 +54,7 @@ private void testCase(FormatterFunc step, String input, PaddedCell.Type expected .rootDir(rootFolder.toPath()) .steps(formatterSteps).build()) { - File file = new File(rootFolder, "input"); + var file = new File(rootFolder, "input"); Files.write(file.toPath(), input.getBytes(StandardCharsets.UTF_8)); PaddedCell result = PaddedCell.check(formatter, file); @@ -117,7 +117,7 @@ void diverging() throws IOException { void cycleOrder() { BiConsumer testCase = (unorderedStr, canonical) -> { List unordered = Arrays.asList(unorderedStr.split(",")); - for (int i = 0; i < unordered.size(); ++i) { + for (var i = 0; i < unordered.size(); ++i) { // try every rotation of the list Collections.rotate(unordered, 1); PaddedCell result = CYCLE.create(rootFolder, unordered); diff --git a/testlib/src/test/java/com/diffplug/spotless/cpp/ClangFormatStepTest.java b/testlib/src/test/java/com/diffplug/spotless/cpp/ClangFormatStepTest.java index 7e76b4eea1..033faab2d2 100644 --- a/testlib/src/test/java/com/diffplug/spotless/cpp/ClangFormatStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/cpp/ClangFormatStepTest.java @@ -32,8 +32,8 @@ void test() { harness.testResource("example.java", "clang/example.java.dirty", "clang/example.java.clean"); // test every other language clang supports for (String ext : Arrays.asList("c", "cs", "js", "m", "proto")) { - String filename = "example." + ext; - String root = "clang/" + filename; + var filename = "example." + ext; + var root = "clang/" + filename; harness.testResource(filename, root, root + ".clean"); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/cpp/CppDefaultsTest.java b/testlib/src/test/java/com/diffplug/spotless/cpp/CppDefaultsTest.java index b384298623..8a3732441d 100644 --- a/testlib/src/test/java/com/diffplug/spotless/cpp/CppDefaultsTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/cpp/CppDefaultsTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ class CppDefaultsTest extends ResourceHarness { @Test void testDelimiterExpr() throws Exception { - final String header = "/*My tests header*/"; + final var header = "/*My tests header*/"; FormatterStep step = LicenseHeaderStep.headerDelimiter(header, CppDefaults.DELIMITER_EXPR).build(); final File dummyFile = setFile("src/main/cpp/file1.dummy").toContent(""); for (String testSource : Arrays.asList( @@ -48,7 +48,7 @@ void testDelimiterExpr() throws Exception { } catch (IllegalArgumentException e) { throw new AssertionError(String.format("No delimiter found in '%s'", testSource), e); } - String expected = testSource.replaceAll("(.*?)\\@", header + '\n'); + var expected = testSource.replaceAll("(.*?)\\@", header + '\n'); assertThat(output).isEqualTo(expected).as("Unexpected header insertion for '$s'.", testSource); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/generic/IndentStepTest.java b/testlib/src/test/java/com/diffplug/spotless/generic/IndentStepTest.java index 38503d7182..bd4f0742a9 100644 --- a/testlib/src/test/java/com/diffplug/spotless/generic/IndentStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/generic/IndentStepTest.java @@ -49,7 +49,7 @@ void tabToSpace() { @Test void doesntClipNewlines() { FormatterStep indent = IndentStep.Type.SPACE.create(4); - String blankNewlines = "\n\n\n\n"; + var blankNewlines = "\n\n\n\n"; StepHarness.forStep(indent).testUnaffected(blankNewlines); } 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 92c6794643..446f099749 100644 --- a/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java @@ -68,7 +68,7 @@ void should_apply_license_containing_YEAR_token() throws Throwable { .test(hasHeaderYear(HEADER_WITH_$YEAR + "\n **/\n/* Something after license.", "2003"), hasHeaderYear("2003")) .test(hasHeaderYear("not a year"), hasHeaderYear(currentYear())); // Check with variant - String otherFakeLicense = "This is a fake license. Copyright $YEAR ACME corp."; + var otherFakeLicense = "This is a fake license. Copyright $YEAR ACME corp."; StepHarness.forStep(LicenseHeaderStep.headerDelimiter(header(otherFakeLicense), package_).build()) .test(getTestResource(FILE_NO_LICENSE), hasHeaderYear(otherFakeLicense, currentYear())) .testUnaffected(hasHeaderYear(otherFakeLicense, currentYear())) @@ -78,7 +78,7 @@ void should_apply_license_containing_YEAR_token() throws Throwable { .test(hasHeader("This is a fake license. CopyrightACME corp."), hasHeaderYear(otherFakeLicense, currentYear())); //Check when token is of the format $today.year - String HEADER_WITH_YEAR_INTELLIJ = "This is a fake license, $today.year. ACME corp."; + var HEADER_WITH_YEAR_INTELLIJ = "This is a fake license, $today.year. ACME corp."; 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()))); } @@ -183,7 +183,7 @@ private static String currentYear() { @Test void efficient() throws Throwable { FormatterStep step = LicenseHeaderStep.headerDelimiter("LicenseHeader\n", "contentstart").build(); - String alreadyCorrect = "LicenseHeader\ncontentstart"; + var alreadyCorrect = "LicenseHeader\ncontentstart"; Assertions.assertEquals(alreadyCorrect, step.format(alreadyCorrect, new File(""))); // If no change is required, it should return the exact same string for efficiency reasons Assertions.assertSame(alreadyCorrect, step.format(alreadyCorrect, new File(""))); @@ -193,7 +193,7 @@ void efficient() throws Throwable { void sanitized() throws Throwable { // The sanitizer should add a \n FormatterStep step = LicenseHeaderStep.headerDelimiter("LicenseHeader", "contentstart").build(); - String alreadyCorrect = "LicenseHeader\ncontentstart"; + var alreadyCorrect = "LicenseHeader\ncontentstart"; Assertions.assertEquals(alreadyCorrect, step.format(alreadyCorrect, new File(""))); Assertions.assertSame(alreadyCorrect, step.format(alreadyCorrect, new File(""))); } @@ -202,7 +202,7 @@ void sanitized() throws Throwable { void sanitizerDoesntGoTooFar() throws Throwable { // if the user wants extra lines after the header, we shouldn't clobber them FormatterStep step = LicenseHeaderStep.headerDelimiter("LicenseHeader\n\n", "contentstart").build(); - String alreadyCorrect = "LicenseHeader\n\ncontentstart"; + var alreadyCorrect = "LicenseHeader\n\ncontentstart"; Assertions.assertEquals(alreadyCorrect, step.format(alreadyCorrect, new File(""))); Assertions.assertSame(alreadyCorrect, step.format(alreadyCorrect, new File(""))); } @@ -249,7 +249,7 @@ void should_apply_license_containing_YEAR_token_in_range() throws Throwable { @Test void should_update_year_for_license_with_address() throws Throwable { - int currentYear = LocalDate.now(ZoneOffset.UTC).getYear(); + var currentYear = LocalDate.now(ZoneOffset.UTC).getYear(); FormatterStep step = LicenseHeaderStep.headerDelimiter(header(licenceWithAddress()), package_).withYearMode(YearMode.UPDATE_TO_TODAY).build(); StepHarness.forStep(step).test( hasHeader(licenceWithAddress().replace("$YEAR", "2015")), diff --git a/testlib/src/test/java/com/diffplug/spotless/json/JacksonJsonStepTest.java b/testlib/src/test/java/com/diffplug/spotless/json/JacksonJsonStepTest.java index be681653e1..e2f5ef7fe5 100644 --- a/testlib/src/test/java/com/diffplug/spotless/json/JacksonJsonStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/json/JacksonJsonStepTest.java @@ -33,8 +33,8 @@ void canSetCustomIndentationLevel() { FormatterStep step = JacksonJsonStep.create(TestProvisioner.mavenCentral()); StepHarness stepHarness = StepHarness.forStep(step); - String before = "json/singletonArrayBefore.json"; - String after = "json/singletonArrayAfter_Jackson.json"; + var before = "json/singletonArrayBefore.json"; + var after = "json/singletonArrayAfter_Jackson.json"; stepHarness.testResource(before, after); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/json/JsonFormatterStepCommonTests.java b/testlib/src/test/java/com/diffplug/spotless/json/JsonFormatterStepCommonTests.java index fbdb6e9a4e..f8ac6935d9 100644 --- a/testlib/src/test/java/com/diffplug/spotless/json/JsonFormatterStepCommonTests.java +++ b/testlib/src/test/java/com/diffplug/spotless/json/JsonFormatterStepCommonTests.java @@ -52,8 +52,8 @@ void canSetCustomIndentationLevel() throws Exception { FormatterStep step = createFormatterStep(6, TestProvisioner.mavenCentral()); StepHarness stepHarness = StepHarness.forStep(step); - String before = "json/singletonArrayBefore.json"; - String after = "json/singletonArrayAfter6Spaces.json"; + var before = "json/singletonArrayBefore.json"; + var after = "json/singletonArrayAfter6Spaces.json"; stepHarness.testResource(before, after); } @@ -62,8 +62,8 @@ void canSetIndentationLevelTo0() throws Exception { FormatterStep step = createFormatterStep(0, TestProvisioner.mavenCentral()); StepHarness stepHarness = StepHarness.forStep(step); - String before = "json/singletonArrayBefore.json"; - String after = "json/singletonArrayAfter0Spaces.json"; + var before = "json/singletonArrayBefore.json"; + var after = "json/singletonArrayAfter0Spaces.json"; stepHarness.testResource(before, after); } @@ -96,8 +96,8 @@ protected StepHarness getStepHarness() { } protected void doWithResource(String name) { - String before = String.format("json/%sBefore.json", name); - String after = String.format("json/%sAfter.json", name); + var before = String.format("json/%sBefore.json", name); + var after = String.format("json/%sAfter.json", name); getStepHarness().testResource(before, after); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/json/JsonSimpleStepTest.java b/testlib/src/test/java/com/diffplug/spotless/json/JsonSimpleStepTest.java index 19edc1a8e8..9701bcc9ca 100644 --- a/testlib/src/test/java/com/diffplug/spotless/json/JsonSimpleStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/json/JsonSimpleStepTest.java @@ -88,8 +88,8 @@ void canSetCustomIndentationLevel() { FormatterStep step = JsonSimpleStep.create(6, TestProvisioner.mavenCentral()); StepHarness stepHarness = StepHarness.forStep(step); - String before = "json/singletonArrayBefore.json"; - String after = "json/singletonArrayAfter6Spaces.json"; + var before = "json/singletonArrayBefore.json"; + var after = "json/singletonArrayAfter6Spaces.json"; stepHarness.testResource(before, after); } @@ -98,8 +98,8 @@ void canSetIndentationLevelTo0() { FormatterStep step = JsonSimpleStep.create(0, TestProvisioner.mavenCentral()); StepHarness stepHarness = StepHarness.forStep(step); - String before = "json/singletonArrayBefore.json"; - String after = "json/singletonArrayAfter0Spaces.json"; + var before = "json/singletonArrayBefore.json"; + var after = "json/singletonArrayAfter0Spaces.json"; stepHarness.testResource(before, after); } @@ -126,8 +126,8 @@ protected FormatterStep create() { } private static void doWithResource(StepHarness stepHarness, String name) { - String before = String.format("json/%sBefore.json", name); - String after = String.format("json/%sAfter.json", name); + var before = String.format("json/%sBefore.json", name); + var after = String.format("json/%sAfter.json", name); stepHarness.testResource(before, after); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/kotlin/DiktatStepTest.java b/testlib/src/test/java/com/diffplug/spotless/kotlin/DiktatStepTest.java index 5055f47e8d..2724a54f08 100644 --- a/testlib/src/test/java/com/diffplug/spotless/kotlin/DiktatStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/kotlin/DiktatStepTest.java @@ -42,7 +42,7 @@ void behavior() { @Test void behaviorConf() throws Exception { - String configPath = "src/main/kotlin/diktat-analysis.yml"; + var configPath = "src/main/kotlin/diktat-analysis.yml"; File conf = setFile(configPath).toResource("kotlin/diktat/diktat-analysis.yml"); FileSignature config = signAsList(conf); diff --git a/testlib/src/test/java/com/diffplug/spotless/npm/EslintFormatterStepTest.java b/testlib/src/test/java/com/diffplug/spotless/npm/EslintFormatterStepTest.java index 631a4beaa7..48cf4503b7 100644 --- a/testlib/src/test/java/com/diffplug/spotless/npm/EslintFormatterStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/npm/EslintFormatterStepTest.java @@ -47,17 +47,17 @@ class EslintJavascriptFormattingStepTest extends NpmFormatterStepCommonTests { @ParameterizedTest(name = "{index}: eslint can be applied using ruleset {0}") @ValueSource(strings = {"custom_rules", "styleguide/airbnb", "styleguide/google", "styleguide/standard", "styleguide/xo"}) void formattingUsingRulesetsFile(String ruleSetName) throws Exception { - String filedir = "npm/eslint/javascript/" + ruleSetName + "/"; + var filedir = "npm/eslint/javascript/" + ruleSetName + "/"; - String testDir = "formatting_ruleset_" + ruleSetName.replace('/', '_') + "/"; + var testDir = "formatting_ruleset_" + ruleSetName.replace('/', '_') + "/"; // File testDirFile = newFolder(testDir); final File eslintRc = createTestFile(filedir + ".eslintrc.js"); // final File eslintRc = setFile(buildDir().getPath() + "/.eslintrc.js").toResource(filedir + ".eslintrc.js"); - final String dirtyFile = filedir + "javascript-es6.dirty"; + final var dirtyFile = filedir + "javascript-es6.dirty"; File dirtyFileFile = setFile(testDir + "test.js").toResource(dirtyFile); - final String cleanFile = filedir + "javascript-es6.clean"; + final var cleanFile = filedir + "javascript-es6.clean"; final FormatterStep formatterStep = EslintFormatterStep.create( devDependenciesForRuleset.get(ruleSetName), @@ -86,9 +86,9 @@ class EslintTypescriptFormattingStepTest extends NpmFormatterStepCommonTests { @ParameterizedTest(name = "{index}: eslint can be applied using ruleset {0}") @ValueSource(strings = {"custom_rules", "styleguide/standard_with_typescript", "styleguide/xo"}) void formattingUsingRulesetsFile(String ruleSetName) throws Exception { - String filedir = "npm/eslint/typescript/" + ruleSetName + "/"; + var filedir = "npm/eslint/typescript/" + ruleSetName + "/"; - String testDir = "formatting_ruleset_" + ruleSetName.replace('/', '_') + "/"; + var testDir = "formatting_ruleset_" + ruleSetName.replace('/', '_') + "/"; // File testDirFile = newFolder(testDir); final File eslintRc = createTestFile(filedir + ".eslintrc.js"); @@ -99,9 +99,9 @@ void formattingUsingRulesetsFile(String ruleSetName) throws Exception { if (existsTestResource(filedir + "tsconfig.json")) { tsconfigFile = setFile(testDir + "tsconfig.json").toResource(filedir + "tsconfig.json"); } - final String dirtyFile = filedir + "typescript.dirty"; + final var dirtyFile = filedir + "typescript.dirty"; File dirtyFileFile = setFile(testDir + "test.ts").toResource(dirtyFile); - final String cleanFile = filedir + "typescript.clean"; + final var cleanFile = filedir + "typescript.clean"; final FormatterStep formatterStep = EslintFormatterStep.create( devDependenciesForRuleset.get(ruleSetName), @@ -124,11 +124,11 @@ class EslintInlineConfigTypescriptFormattingStepTest extends NpmFormatterStepCom @Test void formattingUsingInlineXoConfig() throws Exception { - String filedir = "npm/eslint/typescript/styleguide/xo/"; + var filedir = "npm/eslint/typescript/styleguide/xo/"; - String testDir = "formatting_ruleset_xo_inline_config/"; + var testDir = "formatting_ruleset_xo_inline_config/"; - final String esLintConfig = String.join("\n", + final var esLintConfig = String.join("\n", "{", " env: {", " browser: true,", @@ -157,9 +157,9 @@ void formattingUsingInlineXoConfig() throws Exception { "}"); File tsconfigFile = setFile(testDir + "tsconfig.json").toResource(filedir + "tsconfig.json"); - final String dirtyFile = filedir + "typescript.dirty"; + final var dirtyFile = filedir + "typescript.dirty"; File dirtyFileFile = setFile(testDir + "test.ts").toResource(dirtyFile); - final String cleanFile = filedir + "typescript.clean"; + final var cleanFile = filedir + "typescript.clean"; final FormatterStep formatterStep = EslintFormatterStep.create( EslintStyleGuide.TS_XO_TYPESCRIPT.mergedWith(EslintFormatterStep.defaultDevDependenciesForTypescript()), diff --git a/testlib/src/test/java/com/diffplug/spotless/npm/PrettierFormatterStepTest.java b/testlib/src/test/java/com/diffplug/spotless/npm/PrettierFormatterStepTest.java index c0e587aa98..21cf9b6364 100644 --- a/testlib/src/test/java/com/diffplug/spotless/npm/PrettierFormatterStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/npm/PrettierFormatterStepTest.java @@ -41,11 +41,11 @@ class PrettierFormattingOfFileTypesIsWorking extends NpmFormatterStepCommonTests @ParameterizedTest(name = "{index}: prettier can be applied to {0}") @ValueSource(strings = {"html", "typescript", "json", "javascript-es5", "javascript-es6", "css", "scss", "markdown", "yaml"}) void formattingUsingConfigFile(String fileType) throws Exception { - String filedir = "npm/prettier/filetypes/" + fileType + "/"; + var filedir = "npm/prettier/filetypes/" + fileType + "/"; final File prettierRc = createTestFile(filedir + ".prettierrc.yml"); - final String dirtyFile = filedir + fileType + ".dirty"; - final String cleanFile = filedir + fileType + ".clean"; + final var dirtyFile = filedir + fileType + ".dirty"; + final var cleanFile = filedir + fileType + ".clean"; final FormatterStep formatterStep = PrettierFormatterStep.create( PrettierFormatterStep.defaultDevDependencies(), @@ -68,10 +68,10 @@ class SpecificPrettierFormatterStepTests extends NpmFormatterStepCommonTests { @Test void parserInferenceBasedOnExplicitFilepathIsWorking() throws Exception { - String filedir = "npm/prettier/filetypes/json/"; + var filedir = "npm/prettier/filetypes/json/"; - final String dirtyFile = filedir + "json.dirty"; - final String cleanFile = filedir + "json.clean"; + final var dirtyFile = filedir + "json.dirty"; + final var cleanFile = filedir + "json.clean"; final FormatterStep formatterStep = PrettierFormatterStep.create( PrettierFormatterStep.defaultDevDependencies(), @@ -89,10 +89,10 @@ void parserInferenceBasedOnExplicitFilepathIsWorking() throws Exception { @Test void parserInferenceBasedOnFilenameIsWorking() throws Exception { - String filedir = "npm/prettier/filename/"; + var filedir = "npm/prettier/filename/"; - final String dirtyFile = filedir + "dirty.json"; - final String cleanFile = filedir + "clean.json"; + final var dirtyFile = filedir + "dirty.json"; + final var cleanFile = filedir + "clean.json"; final FormatterStep formatterStep = PrettierFormatterStep.create( PrettierFormatterStep.defaultDevDependencies(), @@ -133,8 +133,8 @@ class PrettierFormattingOptionsAreWorking extends NpmFormatterStepCommonTests { void runFormatTest(PrettierConfig config, String cleanFileNameSuffix) throws Exception { - final String dirtyFile = FILEDIR + "typescript.dirty"; - final String cleanFile = FILEDIR + "typescript." + cleanFileNameSuffix + ".clean"; + final var dirtyFile = FILEDIR + "typescript.dirty"; + final var cleanFile = FILEDIR + "typescript." + cleanFileNameSuffix + ".clean"; final FormatterStep formatterStep = PrettierFormatterStep.create( PrettierFormatterStep.defaultDevDependencies(), diff --git a/testlib/src/test/java/com/diffplug/spotless/npm/ShadowCopyTest.java b/testlib/src/test/java/com/diffplug/spotless/npm/ShadowCopyTest.java index 1ef1b77caa..193d1263ec 100644 --- a/testlib/src/test/java/com/diffplug/spotless/npm/ShadowCopyTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/npm/ShadowCopyTest.java @@ -48,7 +48,7 @@ void setUp() throws IOException { @Test void anAddedEntryCanBeRetrieved() throws IOException { - File folderWithRandomFile = newFolderWithRandomFile(); + var folderWithRandomFile = newFolderWithRandomFile(); shadowCopy.addEntry("someEntry", folderWithRandomFile); File shadowCopyFile = shadowCopy.getEntry("someEntry", folderWithRandomFile.getName()); Assertions.assertThat(shadowCopyFile.listFiles()).hasSize(folderWithRandomFile.listFiles().length); @@ -57,8 +57,8 @@ void anAddedEntryCanBeRetrieved() throws IOException { @Test void twoAddedEntriesCanBeRetrieved() throws IOException { - File folderWithRandomFile = newFolderWithRandomFile(); - File folderWithRandomFile2 = newFolderWithRandomFile(); + var folderWithRandomFile = newFolderWithRandomFile(); + var folderWithRandomFile2 = newFolderWithRandomFile(); shadowCopy.addEntry("someEntry", folderWithRandomFile); shadowCopy.addEntry("someOtherEntry", folderWithRandomFile2); File shadowCopyFile = shadowCopy.getEntry("someEntry", folderWithRandomFile.getName()); @@ -71,7 +71,7 @@ void twoAddedEntriesCanBeRetrieved() throws IOException { @Test void addingTheSameEntryTwiceWorks() throws IOException { - File folderWithRandomFile = newFolderWithRandomFile(); + var folderWithRandomFile = newFolderWithRandomFile(); shadowCopy.addEntry("someEntry", folderWithRandomFile); shadowCopy.addEntry("someEntry", folderWithRandomFile); File shadowCopyFile = shadowCopy.getEntry("someEntry", folderWithRandomFile.getName()); @@ -81,12 +81,12 @@ void addingTheSameEntryTwiceWorks() throws IOException { @Test void changingAFolderAfterAddingItDoesNotChangeTheShadowCopy() throws IOException { - File folderWithRandomFile = newFolderWithRandomFile(); + var folderWithRandomFile = newFolderWithRandomFile(); shadowCopy.addEntry("someEntry", folderWithRandomFile); // now change the orig Files.delete(folderWithRandomFile.listFiles()[0].toPath()); - File newRandomFile = new File(folderWithRandomFile, "replacedFile.txt"); + var newRandomFile = new File(folderWithRandomFile, "replacedFile.txt"); writeRandomStringOfLengthToFile(newRandomFile, 100); // now check that they are different @@ -97,12 +97,12 @@ void changingAFolderAfterAddingItDoesNotChangeTheShadowCopy() throws IOException @Test void addingTheSameEntryTwiceResultsInSecondEntryBeingRetained() throws IOException { - File folderWithRandomFile = newFolderWithRandomFile(); + var folderWithRandomFile = newFolderWithRandomFile(); shadowCopy.addEntry("someEntry", folderWithRandomFile); // now change the orig Files.delete(folderWithRandomFile.listFiles()[0].toPath()); - File newRandomFile = new File(folderWithRandomFile, "replacedFile.txt"); + var newRandomFile = new File(folderWithRandomFile, "replacedFile.txt"); writeRandomStringOfLengthToFile(newRandomFile, 100); // and then add the same entry with new content again and check that they now are the same again @@ -114,7 +114,7 @@ void addingTheSameEntryTwiceResultsInSecondEntryBeingRetained() throws IOExcepti @Test void aFolderCanBeCopiedUsingShadowCopy() throws IOException { - File folderWithRandomFile = newFolderWithRandomFile(); + var folderWithRandomFile = newFolderWithRandomFile(); shadowCopy.addEntry("someEntry", folderWithRandomFile); File copiedFolder = newFolder("copyDest"); File copiedEntry = shadowCopy.copyEntryInto("someEntry", folderWithRandomFile.getName(), copiedFolder); @@ -125,7 +125,7 @@ void aFolderCanBeCopiedUsingShadowCopy() throws IOException { @Test void aCopiedFolderIsDifferentFromShadowCopyEntry() throws IOException { - File folderWithRandomFile = newFolderWithRandomFile(); + var folderWithRandomFile = newFolderWithRandomFile(); shadowCopy.addEntry("someEntry", folderWithRandomFile); File copiedFolder = newFolder("copyDest"); File copiedEntry = shadowCopy.copyEntryInto("someEntry", folderWithRandomFile.getName(), copiedFolder); @@ -137,14 +137,14 @@ void aCopiedFolderIsDifferentFromShadowCopyEntry() throws IOException { @Test void anAddedEntryExistsAfterAdding() throws IOException { - File folderWithRandomFile = newFolderWithRandomFile(); + var folderWithRandomFile = newFolderWithRandomFile(); shadowCopy.addEntry("someEntry", folderWithRandomFile); Assertions.assertThat(shadowCopy.entryExists("someEntry", folderWithRandomFile.getName())).isTrue(); } @Test void aEntryThatHasNotBeenAddedDoesNotExist() throws IOException { - File folderWithRandomFile = newFolderWithRandomFile(); + var folderWithRandomFile = newFolderWithRandomFile(); Assertions.assertThat(shadowCopy.entryExists("someEntry", folderWithRandomFile.getName())).isFalse(); } @@ -162,7 +162,7 @@ private void assertDirectoryIsEqualButNotSameAbsolutePath(File expected, File ac List actualContent = filesInAlphabeticalOrder(actual); List expectedContent = filesInAlphabeticalOrder(expected); - for (int i = 0; i < expectedContent.size(); i++) { + for (var i = 0; i < expectedContent.size(); i++) { assertAllFilesAreEqualButNotSameAbsolutePath(expectedContent.get(i), actualContent.get(i)); } } @@ -184,7 +184,7 @@ private void assertFileIsEqualButNotSameAbsolutePath(File expected, File actual) private File newFolderWithRandomFile() throws IOException { File folder = newFolder(randomStringOfLength(10)); - File file = new File(folder, randomStringOfLength(10) + ".txt"); + var file = new File(folder, randomStringOfLength(10) + ".txt"); writeRandomStringOfLengthToFile(file, 10); return folder; } @@ -196,8 +196,8 @@ private void writeRandomStringOfLengthToFile(File file, int length) throws IOExc private String randomStringOfLength(int length) { // returns a string of length containing characters a-z, A-Z, 0-9 - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { + var sb = new StringBuilder(); + for (var i = 0; i < length; i++) { sb.append(CHARS[random.nextInt(CHARS.length)]); } return sb.toString(); diff --git a/testlib/src/test/java/com/diffplug/spotless/npm/TsFmtFormatterStepTest.java b/testlib/src/test/java/com/diffplug/spotless/npm/TsFmtFormatterStepTest.java index 66fe6e05ac..59cd36cd78 100644 --- a/testlib/src/test/java/com/diffplug/spotless/npm/TsFmtFormatterStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/npm/TsFmtFormatterStepTest.java @@ -41,16 +41,16 @@ class TsFmtUsingVariousFormattingFilesTest extends NpmFormatterStepCommonTests { @ParameterizedTest(name = "{index}: formatting using {0} is working") @ValueSource(strings = {"vscode/vscode.json", "tslint/tslint.json", "tsfmt/tsfmt.json", "tsconfig/tsconfig.json"}) void formattingUsingConfigFile(String formattingConfigFile) throws Exception { - String configFileName = formattingConfigFile.substring(formattingConfigFile.lastIndexOf('/') >= 0 ? formattingConfigFile.lastIndexOf('/') + 1 : 0); - String configFileNameWithoutExtension = configFileName.substring(0, configFileName.lastIndexOf('.')); - String filedir = "npm/tsfmt/" + configFileNameWithoutExtension + "/"; + var configFileName = formattingConfigFile.substring(formattingConfigFile.lastIndexOf('/') >= 0 ? formattingConfigFile.lastIndexOf('/') + 1 : 0); + var configFileNameWithoutExtension = configFileName.substring(0, configFileName.lastIndexOf('.')); + var filedir = "npm/tsfmt/" + configFileNameWithoutExtension + "/"; final File configFile = createTestFile(filedir + configFileName); - final String dirtyFile = filedir + configFileNameWithoutExtension + ".dirty"; - final String cleanFile = filedir + configFileNameWithoutExtension + ".clean"; + final var dirtyFile = filedir + configFileNameWithoutExtension + ".dirty"; + final var cleanFile = filedir + configFileNameWithoutExtension + ".clean"; // some config options expect to see at least one file in the baseDir, so let's write one there - File srcDir = new File(rootFolder(), "src/main/typescript"); + var srcDir = new File(rootFolder(), "src/main/typescript"); Files.createDirectories(srcDir.toPath()); Files.write(new File(srcDir, configFileNameWithoutExtension + ".ts").toPath(), getTestResource(dirtyFile).getBytes(StandardCharsets.UTF_8));