diff --git a/build.gradle b/build.gradle index a20f2b4c74..9a905550cf 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,7 @@ repositories { apply from: rootProject.file('gradle/java-publish.gradle') apply from: rootProject.file('gradle/changelog.gradle') allprojects { + apply from: rootProject.file('gradle/error-prone.gradle') apply from: rootProject.file('gradle/rewrite.gradle') apply from: rootProject.file('gradle/spotless.gradle') } diff --git a/gradle/error-prone.gradle b/gradle/error-prone.gradle new file mode 100644 index 0000000000..9f3fe458c5 --- /dev/null +++ b/gradle/error-prone.gradle @@ -0,0 +1,283 @@ +import static java.lang.System.getenv + +apply plugin: 'net.ltgt.errorprone' + +dependencies { + errorprone('com.google.errorprone:error_prone_core:2.42.0') + errorprone('tech.picnic.error-prone-support:error-prone-contrib:0.25.0') + errorprone('tech.picnic.error-prone-support:refaster-runner:0.25.0') +} + +tasks.withType(JavaCompile).configureEach { + options.errorprone { + allErrorsAsWarnings = true // build will break until complain. + disableWarningsInGeneratedCode = true + disable( + 'DefaultCharset', // contract on ByteArrayOutputStream suggest default encoding. + // bug + 'AddNullMarkedToPackageInfo', + 'Slf4jLogStatement', + ) + error( + 'EmptyMethod', + 'EmptyMonoZip', + 'LexicographicalAnnotationAttributeListing', + 'LexicographicalAnnotationListing', + 'MissingOverride', + 'MissingSuperCall', + 'MissingTestCall', + 'NonEmptyMono', + 'OptionalMapUnusedValue', + 'OptionalOfRedundantMethod', + 'RedundantSetterCall', + 'RedundantStringConversion', + 'RedundantStringEscape', + 'StaticImport', + 'StringJoin', + 'UnnecessaryCheckNotNull', + 'UnnecessaryTypeArgument', + 'UnusedAnonymousClass', + 'UnusedCollectionModifiedInPlace', + ) + errorproneArgs.add('-XepOpt:Refaster:NamePattern=^(?!.*Rules\\$).*') // might consider. + // dev opt-in + if (!getenv().containsKey('CI') && getenv('IN_PLACE')?.toBoolean()) { + // apply + errorproneArgs.addAll( + '-XepPatchLocation:IN_PLACE', + '-XepPatchChecks:' + + 'StaticImport,' + + 'EmptyMethod,' + + 'EmptyMonoZip,' + + 'LexicographicalAnnotationAttributeListing,' + + 'LexicographicalAnnotationListing,' + + 'MissingOverride,' + + 'MissingSuperCall,' + + 'MissingTestCall,' + + 'NonEmptyMono,' + + 'OptionalMapUnusedValue,' + + 'OptionalOfRedundantMethod,' + + 'RedundantSetterCall,' + + 'RedundantStringConversion,' + + 'RedundantStringEscape,' + + 'StringJoin,' + + 'UnnecessaryCheckNotNull,' + + 'UnnecessaryTypeArgument,' + + 'UnusedAnonymousClass,' + + 'UnusedCollectionModifiedInPlace,' + // 'AddNullMarkedToPackageInfo,' + + // 'AlwaysThrows,' + + // 'AmbiguousJsonCreator,' + + // 'AndroidInjectionBeforeSuper,' + + // 'ArrayEquals,' + + // 'ArrayFillIncompatibleType,' + + // 'ArrayHashCode,' + + // 'ArrayToString,' + + // 'ArraysAsListPrimitiveArray,' + + // 'AssertJNullnessAssertion,' + + // 'AsyncCallableReturnsNull,' + + // 'AsyncFunctionReturnsNull,' + + // 'AutoValueBuilderDefaultsInConstructor,' + + // 'AutoValueConstructorOrderChecker,' + + // 'AutowiredConstructor,' + + // 'BadAnnotationImplementation,' + + // 'BadShiftAmount,' + + // 'BanJNDI,' + + // 'BoxedPrimitiveEquality,' + + // 'BundleDeserializationCast,' + + // 'CanonicalAnnotationSyntax,' + + // 'CanonicalClassNameUsage,' + + // 'ChainingConstructorIgnoresParameter,' + + // 'CheckNotNullMultipleTimes,' + + // 'CheckReturnValue,' + + // 'ClassCastLambdaUsage,' + + // 'CollectionIncompatibleType,' + + // 'CollectionToArraySafeParameter,' + + // 'CollectorMutability,' + + // 'ComparableType,' + + // 'ComparingThisWithNull,' + + // 'ComparisonOutOfRange,' + + // 'CompatibleWithAnnotationMisuse,' + + // 'CompileTimeConstant,' + + // 'ComputeIfAbsentAmbiguousReference,' + + // 'ConditionalExpressionNumericPromotion,' + + // 'ConstantNaming,' + + // 'ConstantOverflow,' + + // 'DaggerProvidesNull,' + + // 'DangerousLiteralNull,' + + // 'DeadException,' + + // 'DeadThread,' + + // 'DereferenceWithNullBranch,' + + // 'DirectReturn,' + + // 'DiscardedPostfixExpression,' + + // 'DoNotCall,' + + // 'DoNotMock,' + + // 'DoubleBraceInitialization,' + + // 'DuplicateMapKeys,' + + // 'DurationFrom,' + + // 'DurationGetTemporalUnit,' + + // 'DurationTemporalUnit,' + + // 'DurationToLongTimeUnit,' + + // 'EagerStringFormatting,' + + // 'EqualsHashCode,' + + // 'EqualsNaN,' + + // 'EqualsNull,' + + // 'EqualsReference,' + + // 'EqualsWrongThing,' + + // 'ExplicitArgumentEnumeration,' + + // 'ExplicitEnumOrdering,' + + // 'FloggerFormatString,' + + // 'FloggerLogString,' + + // 'FloggerLogVarargs,' + + // 'FloggerSplitLogStatement,' + + // 'FluxFlatMapUsage,' + + // 'FluxImplicitBlock,' + + // 'ForOverride,' + + // 'FormatString,' + + // 'FormatStringAnnotation,' + + // 'FormatStringConcatenation,' + + // 'FromTemporalAccessor,' + + // 'FunctionalInterfaceMethodChanged,' + + // 'FunctionalInterfaceMethodChanged,' + + // 'FuturesGetCheckedIllegalExceptionType,' + + // 'FuzzyEqualsShouldNotBeUsedInEqualsMethod,' + + // 'GetClassOnAnnotation,' + + // 'GetClassOnClass,' + + // 'GuardedBy,' + + // 'GuiceAssistedInjectScoping,' + + // 'GuiceAssistedParameters,' + + // 'GuiceInjectOnFinalField,' + + // 'HashtableContains,' + + // 'IdentityBinaryExpression,' + + // 'IdentityConversion,' + + // 'IdentityHashMapBoxing,' + + // 'Immutable,' + + // 'ImmutableEnumChecker,' + + // 'ImmutablesSortedSetComparator,' + + // 'ImpossibleNullComparison,' + + // 'Incomparable,' + + // 'IncompatibleArgumentType,' + + // 'IncompatibleModifiers,' + + // 'IndexOfChar,' + + // 'InexactVarargsConditional,' + + // 'InfiniteRecursion,' + + // 'InjectMoreThanOneScopeAnnotationOnClass,' + + // 'InjectOnMemberAndConstructor,' + + // 'InlineMeValidator,' + + // 'InstantTemporalUnit,' + + // 'InvalidJavaTimeConstant,' + + // 'InvalidPatternSyntax,' + + // 'InvalidTimeZoneID,' + + // 'InvalidZoneId,' + + // 'IsInstanceIncompatibleType,' + + // 'IsInstanceLambdaUsage,' + + // 'IsInstanceOfClass,' + + // 'IsLoggableTagLength,' + + // 'JUnit3TestNotRun,' + + // 'JUnit4ClassAnnotationNonStatic,' + + // 'JUnit4SetUpNotRun,' + + // 'JUnit4TearDownNotRun,' + + // 'JUnit4TestNotRun,' + + // 'JUnit4TestsNotRunWithinEnclosed,' + + // 'JUnitAssertSameCheck,' + + // 'JUnitClassModifiers,' + + // 'JUnitMethodDeclaration,' + + // 'JUnitNullaryParameterizedTestDeclaration,' + + // 'JUnitParameterMethodNotFound,' + + // 'JUnitValueSource,' + + // 'JavaxInjectOnAbstractMethod,' + + // 'JodaToSelf,' + + // 'LenientFormatStringValidation,' + + // 'LiteByteStringUtf8,' + + // 'LocalDateTemporalAmount,' + + // 'LockOnBoxedPrimitive,' + + // 'LoopConditionChecker,' + + // 'LossyPrimitiveCompare,' + + // 'MathRoundIntLong,' + + // 'MislabeledAndroidString,' + + // 'MisleadingEmptyVarargs,' + + // 'MisleadingEscapedSpace,' + + // 'MisplacedScopeAnnotations,' + + // 'MisusedDayOfYear,' + + // 'MisusedWeekYear,' + + // 'MixedDescriptors,' + + // 'MockitoMockClassReference,' + + // 'MockitoStubbing,' + + // 'MockitoUsage,' + + // 'ModifyingCollectionWithItself,' + + // 'MongoDBTextFilterUsage,' + + // 'MoreThanOneInjectableConstructor,' + + // 'MustBeClosedChecker,' + + // 'NCopiesOfChar,' + + // 'NestedOptionals,' + + // 'NestedPublishers,' + + // 'NoCanIgnoreReturnValueOnClasses,' + + // 'NonCanonicalStaticImport,' + + // 'NonFinalCompileTimeConstant,' + + // 'NonRuntimeAnnotation,' + + // 'NonStaticImport,' + + // 'NullArgumentForNonNullParameter,' + + // 'NullTernary,' + + // 'NullableOnContainingClass,' + + // 'OptionalEquality,' + + // 'OptionalOrElseGet,' + + // 'OverlappingQualifierAndScopeAnnotation,' + + // 'OverridesJavaxInjectableMethod,' + + // 'PackageInfo,' + + // 'ParametersButNotParameterized,' + + // 'ParcelableCreator,' + + // 'PeriodFrom,' + + // 'PeriodGetTemporalUnit,' + + // 'PeriodTimeMath,' + + // 'PreconditionsInvalidPlaceholder,' + + // 'PrimitiveComparison,' + + // 'PrivateSecurityContractProtoAccess,' + + // 'ProtoBuilderReturnValueIgnored,' + + // 'ProtoStringFieldReferenceEquality,' + + // 'ProtoTruthMixedDescriptors,' + + // 'ProtocolBufferOrdinal,' + + // 'ProvidesMethodOutsideOfModule,' + + // 'RandomCast,' + + // 'RandomModInteger,' + + // 'RectIntersectReturnValueIgnored,' + + // 'RefasterAnyOfUsage,' + + // 'RequestMappingAnnotation,' + + // 'RequestParamType,' + + // 'RequiredModifiers,' + + // 'RestrictedApi,' + + // 'ReturnValueIgnored,' + + // 'SelfAssertion,' + + // 'SelfAssignment,' + + // 'SelfComparison,' + + // 'SelfEquals,' + + // 'SetUnrecognized,' + + // 'ShouldHaveEvenArgs,' + + // 'SizeGreaterThanOrEqualsZero,' + + // 'Slf4jLogStatement,' + + // 'Slf4jLoggerDeclarationSlf4jLoggerDeclaration,' + + // 'SpringMvcAnnotation,' + + // 'StreamToString,' + + // 'StringBuilderInitWithChar,' + + // 'SubstringOfZero,' + + // 'SuppressWarningsDeprecated,' + + // 'TemporalAccessorGetChronoField,' + + // 'TestParametersNotInitialized,' + + // 'TheoryButNoTheories,' + + // 'ThreadBuilderNameWithPlaceholder,' + + // 'ThrowIfUncheckedKnownChecked,' + + // 'ThrowNull,' + + // 'TimeZoneUsage,' + + // 'TreeToString,' + + // 'TryFailThrowable,' + + // 'TypeParameterQualifier,' + + // 'UnicodeDirectionalityCharacters,' + + // 'UnicodeInCode,' + + // 'UnsafeWildcard,' + + // 'VarTypeName,' + + // 'WrongOneof,' + + // 'XorPower,' + + // 'ZoneIdOfZ,' + ) + } + } +} diff --git a/lib-extra/src/cdt/java/com/diffplug/spotless/extra/glue/cdt/EclipseCdtFormatterStepImpl.java b/lib-extra/src/cdt/java/com/diffplug/spotless/extra/glue/cdt/EclipseCdtFormatterStepImpl.java index 045860f535..19144845cd 100644 --- a/lib-extra/src/cdt/java/com/diffplug/spotless/extra/glue/cdt/EclipseCdtFormatterStepImpl.java +++ b/lib-extra/src/cdt/java/com/diffplug/spotless/extra/glue/cdt/EclipseCdtFormatterStepImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,11 @@ */ package com.diffplug.spotless.extra.glue.cdt; +import static java.util.stream.Collectors.toMap; + import java.util.Map; import java.util.Map.Entry; import java.util.Properties; -import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.cdt.core.formatter.CodeFormatter; @@ -32,7 +33,7 @@ public class EclipseCdtFormatterStepImpl { public EclipseCdtFormatterStepImpl(Properties settings) throws Exception { Stream> stream = settings.entrySet().stream(); - Map settingsMap = stream.collect(Collectors.toMap( + Map settingsMap = stream.collect(toMap( e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()))); codeFormatter = org.eclipse.cdt.core.ToolFactory.createDefaultCodeFormatter(settingsMap); 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 682e9bddbb..1a9ea08424 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 @@ -15,12 +15,13 @@ */ package com.diffplug.spotless.extra.glue.groovy; +import static java.util.Collections.synchronizedList; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Properties; @@ -111,7 +112,7 @@ public GroovyErrorListener() { * We need a synchronized list here, in case multiple instantiations * run in parallel. */ - errors = Collections.synchronizedList(new ArrayList<>()); + errors = synchronizedList(new ArrayList<>()); ILog groovyLogger = GroovyCoreActivator.getDefault().getLog(); groovyLogger.addLogListener(this); synchronized (GroovyLogManager.manager) { diff --git a/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/EclipseJdtFormatterStepImpl.java b/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/EclipseJdtFormatterStepImpl.java index 39a493e63b..5566222f15 100644 --- a/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/EclipseJdtFormatterStepImpl.java +++ b/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/EclipseJdtFormatterStepImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,11 +15,12 @@ */ package com.diffplug.spotless.extra.glue.jdt; +import static java.util.stream.Collectors.toMap; + import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Properties; -import java.util.stream.Collectors; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jdt.internal.compiler.env.IModule; @@ -37,7 +38,7 @@ public class EclipseJdtFormatterStepImpl { private final EclipseJdtSortMembers.SortProperties sortProperties; public EclipseJdtFormatterStepImpl(Properties formatterSettings, Map sortProperties) { - Map options = formatterSettings.entrySet().stream().collect(Collectors.toMap( + Map options = formatterSettings.entrySet().stream().collect(toMap( e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()), (prev, next) -> next, diff --git a/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/EclipseJdtSortMembers.java b/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/EclipseJdtSortMembers.java index 5c75a62344..a50c41a454 100644 --- a/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/EclipseJdtSortMembers.java +++ b/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/EclipseJdtSortMembers.java @@ -98,64 +98,84 @@ private static class Buffer implements IBuffer { this.contents = contents; } + @Override public void addBufferChangedListener(IBufferChangedListener listener) {} + @Override public void append(char[] text) {} + @Override public void append(String text) {} + @Override public void close() {} + @Override public char getChar(int position) { return '\u0000'; } + @Override public char[] getCharacters() { return contents.toCharArray(); } + @Override public String getContents() { return contents; } + @Override public int getLength() { return 0; } + @Override public IOpenable getOwner() { return null; } + @Override public String getText(int offset, int length) { return null; } + @Override public IResource getUnderlyingResource() { return null; } + @Override public boolean hasUnsavedChanges() { return false; } + @Override public boolean isClosed() { return false; } + @Override public boolean isReadOnly() { return true; } + @Override public void removeBufferChangedListener(IBufferChangedListener listener) {} + @Override public void replace(int position, int length, char[] text) {} + @Override public void replace(int position, int length, String text) {} + @Override public void save(IProgressMonitor progress, boolean force) {} + @Override public void setContents(char[] contents) {} + @Override public void setContents(String contents) { this.contents = contents; } 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 2c3d1a5a6c..3f7599c6b2 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 @@ -15,15 +15,16 @@ */ package com.diffplug.spotless.extra; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; + import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.Properties; import com.diffplug.common.base.Errors; @@ -69,10 +70,10 @@ public EclipseBasedStepBuilder(String formatterName, Provisioner jarProvisioner, /** Initialize valid default configuration, taking latest version */ public EclipseBasedStepBuilder(String formatterName, String formatterStepExt, Provisioner jarProvisioner, SerializedFunction stateToFormatter) { - this.formatterName = Objects.requireNonNull(formatterName, "formatterName"); - this.formatterStepExt = Objects.requireNonNull(formatterStepExt, "formatterStepExt"); - this.jarProvisioner = Objects.requireNonNull(jarProvisioner, "jarProvisioner"); - this.stateToFormatter = Objects.requireNonNull(stateToFormatter, "stateToFormatter"); + this.formatterName = requireNonNull(formatterName, "formatterName"); + this.formatterStepExt = requireNonNull(formatterStepExt, "formatterStepExt"); + this.jarProvisioner = requireNonNull(jarProvisioner, "jarProvisioner"); + this.stateToFormatter = requireNonNull(stateToFormatter, "stateToFormatter"); formatterVersion = "No version set"; //Will fail creation } @@ -91,7 +92,7 @@ public void setVersion(String version) { throw new IllegalArgumentException("No such version " + version + ", expected at " + url); } byte[] content = toByteArray(depsFile); - String allLines = new String(content, StandardCharsets.UTF_8); + String allLines = new String(content, UTF_8); String[] lines = allLines.split("\n"); dependencies.clear(); for (String line : lines) { 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 c4c41e41df..85a8feb392 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 @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.extra; +import static java.util.Objects.requireNonNullElse; import static java.util.stream.Collectors.toMap; import java.io.File; @@ -24,7 +25,6 @@ import java.util.Collection; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Properties; import javax.annotation.Nullable; @@ -190,8 +190,8 @@ static class EquoStep implements Serializable { ImmutableMap stepProperties) { this.semanticVersion = semanticVersion; - this.settingProperties = Objects.requireNonNullElse(settingProperties, new ArrayList<>()); - this.settingXml = Objects.requireNonNullElse(settingXml, new ArrayList<>()); + this.settingProperties = requireNonNullElse(settingProperties, new ArrayList<>()); + this.settingXml = requireNonNullElse(settingXml, new ArrayList<>()); this.settingsPromise = settingsPromise; this.jarPromise = jarPromise; this.stepProperties = stepProperties; @@ -218,8 +218,8 @@ public static class State implements Serializable { public State(String semanticVersion, JarState jarState, List settingProperties, List settingXml, FileSignature settingsFiles, ImmutableMap stepProperties) { this.semanticVersion = semanticVersion; this.jarState = jarState; - this.settingProperties = Objects.requireNonNullElse(settingProperties, new ArrayList<>()); - this.settingXml = Objects.requireNonNullElse(settingXml, new ArrayList<>()); + this.settingProperties = requireNonNullElse(settingProperties, new ArrayList<>()); + this.settingXml = requireNonNullElse(settingXml, new ArrayList<>()); this.settingsFiles = settingsFiles; this.stepProperties = stepProperties; } diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java index af027ad42d..a78cc0e4c0 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 @@ -15,17 +15,18 @@ */ package com.diffplug.spotless.extra; +import static java.util.Collections.emptyList; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.Objects; import java.util.function.Supplier; import javax.annotation.Nullable; @@ -120,8 +121,8 @@ static class RelocatablePolicy extends LazyForwardingEquality imp transient Supplier> toFormat; RelocatablePolicy(File projectDir, Supplier> toFormat) { - this.projectDir = Objects.requireNonNull(projectDir, "projectDir"); - this.toFormat = Objects.requireNonNull(toFormat, "toFormat"); + this.projectDir = requireNonNull(projectDir, "projectDir"); + this.toFormat = requireNonNull(toFormat, "toFormat"); } @Override @@ -260,10 +261,10 @@ static final class Runtime { final String defaultEnding; private Runtime(List infoRules, @Nullable File workTree, Config config, List globalRules) { - this.infoRules = Objects.requireNonNull(infoRules); + this.infoRules = requireNonNull(infoRules); this.workTree = workTree; this.defaultEnding = findDefaultLineEnding(config).str(); - this.globalRules = Objects.requireNonNull(globalRules); + this.globalRules = requireNonNull(globalRules); } private static final String KEY_EOL = "eol"; @@ -389,7 +390,7 @@ private static List parseRules(@Nullable File file) { LOGGER.warn("Problem parsing {}", file.getAbsolutePath(), e); } } - return Collections.emptyList(); + return emptyList(); } /** Parses an attribute value from a list of rules, returning null if there is no match for the given key. */ 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 97c95615fb..5857deac25 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 @@ -202,8 +202,8 @@ private static IOException emptyFile(File commonDir) { return new IOException("Empty 'commondir' file: " + commonDir.getAbsolutePath()); } - @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE") @Override + @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE") public FileRepositoryBuilder readEnvironment(SystemReader sr) { super.readEnvironment(sr); diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/LibExtraPreconditions.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/LibExtraPreconditions.java index 711f6e4d5c..15716a4909 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/LibExtraPreconditions.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/LibExtraPreconditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,16 +15,16 @@ */ package com.diffplug.spotless.extra; -import java.util.Objects; +import static java.util.Objects.requireNonNull; final class LibExtraPreconditions { // prevent direct instantiation private LibExtraPreconditions() {} static > I requireElementsNonNull(I elements) { - Objects.requireNonNull(elements); + requireNonNull(elements); for (Object element : elements) { - Objects.requireNonNull(element); + requireNonNull(element); } return elements; } 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 fb9d176eac..f1a420641d 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 @@ -15,6 +15,9 @@ */ package com.diffplug.spotless.extra.integration; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; + import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -25,7 +28,6 @@ import java.util.List; import java.util.ListIterator; import java.util.Map; -import java.util.Objects; import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.diff.Edit; @@ -62,8 +64,8 @@ private static class CleanProviderFormatter implements CleanProvider { private final Formatter formatter; CleanProviderFormatter(Path rootDir, Formatter formatter) { - this.rootDir = Objects.requireNonNull(rootDir); - this.formatter = Objects.requireNonNull(formatter); + this.rootDir = requireNonNull(rootDir); + this.formatter = requireNonNull(formatter); } @Override @@ -121,7 +123,7 @@ private Builder() {} /** "Run 'gradlew spotlessApply' to fix these violations." */ public Builder runToFix(String runToFix) { - this.runToFix = Objects.requireNonNull(runToFix); + this.runToFix = requireNonNull(runToFix); return this; } @@ -136,7 +138,7 @@ public Builder formatterFolder(Path rootDir, Path cleanDir, String encoding) { } public Builder problemFiles(List problemFiles) { - this.problemFiles = Objects.requireNonNull(problemFiles); + this.problemFiles = requireNonNull(problemFiles); Preconditions.checkArgument(!problemFiles.isEmpty(), "cannot be empty"); return this; } @@ -144,9 +146,9 @@ public Builder problemFiles(List problemFiles) { /** Returns the error message. */ public String getMessage() { try { - Objects.requireNonNull(runToFix, "runToFix"); - Objects.requireNonNull(formatter, "formatter"); - Objects.requireNonNull(problemFiles, "problemFiles"); + requireNonNull(runToFix, "runToFix"); + requireNonNull(formatter, "formatter"); + requireNonNull(problemFiles, "problemFiles"); DiffMessageFormatter diffFormater = new DiffMessageFormatter(formatter, problemFiles); return "The following files had format violations:\n" + diffFormater.buffer @@ -166,7 +168,7 @@ public String getMessage() { private final CleanProvider formatter; private DiffMessageFormatter(CleanProvider formatter, List problemFiles) throws IOException { - this.formatter = Objects.requireNonNull(formatter, "formatter"); + this.formatter = requireNonNull(formatter, "formatter"); ListIterator problemIter = problemFiles.listIterator(); while (problemIter.hasNext() && numLines < MAX_CHECK_MESSAGE_LINES) { File file = problemIter.next(); @@ -275,8 +277,8 @@ private static Map.Entry diffWhitespaceLineEndings(String dirty dirty = visibleWhitespaceLineEndings(dirty, whitespace, lineEndings); clean = visibleWhitespaceLineEndings(clean, whitespace, lineEndings); - RawText a = new RawText(dirty.getBytes(StandardCharsets.UTF_8)); - RawText b = new RawText(clean.getBytes(StandardCharsets.UTF_8)); + RawText a = new RawText(dirty.getBytes(UTF_8)); + RawText b = new RawText(clean.getBytes(UTF_8)); EditList edits = new EditList(); edits.addAll(MyersDiff.INSTANCE.diff(RawTextComparator.DEFAULT, a, b)); 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 8af0478543..344941dca8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,14 @@ */ package com.diffplug.spotless.extra; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.assertj.core.api.Assertions; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.junit.jupiter.api.Test; @@ -56,27 +57,27 @@ void cacheTest() { "*.MF eol=crlf")); { GitAttributesLineEndings.AttributesCache cache = new GitAttributesLineEndings.AttributesCache(); - Assertions.assertThat(cache.valueFor(newFile("someFile"), "eol")).isEqualTo("lf"); - Assertions.assertThat(cache.valueFor(newFile("subfolder/someFile"), "eol")).isEqualTo("lf"); - Assertions.assertThat(cache.valueFor(newFile("MANIFEST.MF"), "eol")).isEqualTo("crlf"); - Assertions.assertThat(cache.valueFor(newFile("subfolder/MANIFEST.MF"), "eol")).isEqualTo("crlf"); + assertThat(cache.valueFor(newFile("someFile"), "eol")).isEqualTo("lf"); + assertThat(cache.valueFor(newFile("subfolder/someFile"), "eol")).isEqualTo("lf"); + assertThat(cache.valueFor(newFile("MANIFEST.MF"), "eol")).isEqualTo("crlf"); + assertThat(cache.valueFor(newFile("subfolder/MANIFEST.MF"), "eol")).isEqualTo("crlf"); // write out a .gitattributes for the subfolder setFile("subfolder/.gitattributes").toContent("* eol=lf"); // it shouldn't change anything, because it's cached - Assertions.assertThat(cache.valueFor(newFile("someFile"), "eol")).isEqualTo("lf"); - Assertions.assertThat(cache.valueFor(newFile("subfolder/someFile"), "eol")).isEqualTo("lf"); - Assertions.assertThat(cache.valueFor(newFile("MANIFEST.MF"), "eol")).isEqualTo("crlf"); - Assertions.assertThat(cache.valueFor(newFile("subfolder/MANIFEST.MF"), "eol")).isEqualTo("crlf"); + assertThat(cache.valueFor(newFile("someFile"), "eol")).isEqualTo("lf"); + assertThat(cache.valueFor(newFile("subfolder/someFile"), "eol")).isEqualTo("lf"); + assertThat(cache.valueFor(newFile("MANIFEST.MF"), "eol")).isEqualTo("crlf"); + assertThat(cache.valueFor(newFile("subfolder/MANIFEST.MF"), "eol")).isEqualTo("crlf"); } { // but if we make a new cache, it should change GitAttributesLineEndings.AttributesCache cache = new GitAttributesLineEndings.AttributesCache(); - Assertions.assertThat(cache.valueFor(newFile("someFile"), "eol")).isEqualTo("lf"); - Assertions.assertThat(cache.valueFor(newFile("subfolder/someFile"), "eol")).isEqualTo("lf"); - Assertions.assertThat(cache.valueFor(newFile("MANIFEST.MF"), "eol")).isEqualTo("crlf"); - Assertions.assertThat(cache.valueFor(newFile("subfolder/MANIFEST.MF"), "eol")).isEqualTo("lf"); + assertThat(cache.valueFor(newFile("someFile"), "eol")).isEqualTo("lf"); + assertThat(cache.valueFor(newFile("subfolder/someFile"), "eol")).isEqualTo("lf"); + assertThat(cache.valueFor(newFile("MANIFEST.MF"), "eol")).isEqualTo("crlf"); + assertThat(cache.valueFor(newFile("subfolder/MANIFEST.MF"), "eol")).isEqualTo("lf"); } } @@ -86,10 +87,10 @@ void policyTest() { "* eol=lf", "*.MF eol=crlf")); LineEnding.Policy policy = LineEnding.GIT_ATTRIBUTES.createPolicy(rootFolder(), () -> testFiles()); - Assertions.assertThat(policy.getEndingFor(newFile("someFile"))).isEqualTo("\n"); - Assertions.assertThat(policy.getEndingFor(newFile("subfolder/someFile"))).isEqualTo("\n"); - Assertions.assertThat(policy.getEndingFor(newFile("MANIFEST.MF"))).isEqualTo("\r\n"); - Assertions.assertThat(policy.getEndingFor(newFile("subfolder/MANIFEST.MF"))).isEqualTo("\r\n"); + assertThat(policy.getEndingFor(newFile("someFile"))).isEqualTo("\n"); + assertThat(policy.getEndingFor(newFile("subfolder/someFile"))).isEqualTo("\n"); + assertThat(policy.getEndingFor(newFile("MANIFEST.MF"))).isEqualTo("\r\n"); + assertThat(policy.getEndingFor(newFile("subfolder/MANIFEST.MF"))).isEqualTo("\r\n"); } @Test @@ -101,7 +102,7 @@ void policyDefaultLineEndingTest() throws GitAPIException { "autocrlf=true", "eol=lf")); LineEnding.Policy policy = LineEnding.GIT_ATTRIBUTES.createPolicy(rootFolder(), () -> testFiles()); - Assertions.assertThat(policy.getEndingFor(newFile("someFile"))).isEqualTo("\r\n"); + assertThat(policy.getEndingFor(newFile("someFile"))).isEqualTo("\r\n"); } @Test @@ -114,10 +115,10 @@ void policyTestWithExternalGitDir() throws IOException, GitAPIException { "* eol=lf", "*.MF eol=crlf")); LineEnding.Policy policy = LineEnding.GIT_ATTRIBUTES.createPolicy(projectFolder, () -> testFiles("project/")); - Assertions.assertThat(policy.getEndingFor(newFile("project/someFile"))).isEqualTo("\n"); - Assertions.assertThat(policy.getEndingFor(newFile("project/subfolder/someFile"))).isEqualTo("\n"); - Assertions.assertThat(policy.getEndingFor(newFile("project/MANIFEST.MF"))).isEqualTo("\r\n"); - Assertions.assertThat(policy.getEndingFor(newFile("project/subfolder/MANIFEST.MF"))).isEqualTo("\r\n"); + assertThat(policy.getEndingFor(newFile("project/someFile"))).isEqualTo("\n"); + assertThat(policy.getEndingFor(newFile("project/subfolder/someFile"))).isEqualTo("\n"); + assertThat(policy.getEndingFor(newFile("project/MANIFEST.MF"))).isEqualTo("\r\n"); + assertThat(policy.getEndingFor(newFile("project/subfolder/MANIFEST.MF"))).isEqualTo("\r\n"); } @Test @@ -136,9 +137,9 @@ void policyTestWithCommonDir() throws IOException, GitAPIException { "* eol=lf", "*.MF eol=crlf")); LineEnding.Policy policy = LineEnding.GIT_ATTRIBUTES.createPolicy(projectFolder, () -> testFiles("project/")); - Assertions.assertThat(policy.getEndingFor(newFile("project/someFile"))).isEqualTo("\n"); - Assertions.assertThat(policy.getEndingFor(newFile("project/subfolder/someFile"))).isEqualTo("\n"); - Assertions.assertThat(policy.getEndingFor(newFile("project/MANIFEST.MF"))).isEqualTo("\r\n"); - Assertions.assertThat(policy.getEndingFor(newFile("project/subfolder/MANIFEST.MF"))).isEqualTo("\r\n"); + assertThat(policy.getEndingFor(newFile("project/someFile"))).isEqualTo("\n"); + assertThat(policy.getEndingFor(newFile("project/subfolder/someFile"))).isEqualTo("\n"); + assertThat(policy.getEndingFor(newFile("project/MANIFEST.MF"))).isEqualTo("\r\n"); + assertThat(policy.getEndingFor(newFile("project/subfolder/MANIFEST.MF"))).isEqualTo("\r\n"); } } diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/GitWorkaroundsTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/GitWorkaroundsTest.java index b8a1bf8c89..2a8edd995c 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/GitWorkaroundsTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/GitWorkaroundsTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2022-2024 DiffPlug + * Copyright 2022-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,11 @@ */ package com.diffplug.spotless.extra; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.File; import java.io.IOException; -import org.assertj.core.api.Assertions; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.Constants; @@ -39,7 +40,7 @@ void inline() throws IOException, GitAPIException { Git.init().setDirectory(projectFolder).call(); RepositorySpecificResolver repositorySpecificResolver = GitWorkarounds.fileRepositoryResolverForProject(projectFolder); - Assertions.assertThat(repositorySpecificResolver.getGitDir()).isEqualTo(new File(projectFolder, ".git")); + assertThat(repositorySpecificResolver.getGitDir()).isEqualTo(new File(projectFolder, ".git")); } @Test @@ -49,11 +50,11 @@ void external() throws IOException, GitAPIException { Git.init().setDirectory(projectFolder).setGitDir(gitDir).call(); RepositorySpecificResolver repositorySpecificResolver = GitWorkarounds.fileRepositoryResolverForProject(projectFolder); - Assertions.assertThat(repositorySpecificResolver.getGitDir()).isEqualTo(gitDir); + assertThat(repositorySpecificResolver.getGitDir()).isEqualTo(gitDir); } - @Nested @DisplayName("Worktrees") + @Nested class Worktrees { private File project1Tree; private File project1GitDir; @@ -87,15 +88,15 @@ void resolveGitDir() { // Test worktree 1 { RepositorySpecificResolver repositorySpecificResolver = GitWorkarounds.fileRepositoryResolverForProject(project1Tree); - Assertions.assertThat(repositorySpecificResolver.getGitDir()).isEqualTo(project1GitDir); - Assertions.assertThat(repositorySpecificResolver.resolveWithCommonDir(Constants.CONFIG)).isEqualTo(new File(commonGitDir, Constants.CONFIG)); + assertThat(repositorySpecificResolver.getGitDir()).isEqualTo(project1GitDir); + assertThat(repositorySpecificResolver.resolveWithCommonDir(Constants.CONFIG)).isEqualTo(new File(commonGitDir, Constants.CONFIG)); } // Test worktree 2 { RepositorySpecificResolver repositorySpecificResolver = GitWorkarounds.fileRepositoryResolverForProject(project2Tree); - Assertions.assertThat(repositorySpecificResolver.getGitDir()).isEqualTo(project2GitDir); - Assertions.assertThat(repositorySpecificResolver.resolveWithCommonDir(Constants.CONFIG)).isEqualTo(new File(commonGitDir, Constants.CONFIG)); + assertThat(repositorySpecificResolver.getGitDir()).isEqualTo(project2GitDir); + assertThat(repositorySpecificResolver.resolveWithCommonDir(Constants.CONFIG)).isEqualTo(new File(commonGitDir, Constants.CONFIG)); } } @@ -103,20 +104,20 @@ void resolveGitDir() { void perWorktreeConfig() throws IOException { setFile("project.git/config").toLines("[core]", "mySetting = true"); - Assertions.assertThat(getMySetting(project1Tree)).isTrue(); - Assertions.assertThat(getMySetting(project2Tree)).isTrue(); + assertThat(getMySetting(project1Tree)).isTrue(); + assertThat(getMySetting(project2Tree)).isTrue(); // Override setting for project 1, but don't enable extension yet setFile("project.git/worktrees/project-w1/config.worktree").toLines("[core]", "mySetting = false"); - Assertions.assertThat(getMySetting(project1Tree)).isTrue(); - Assertions.assertThat(getMySetting(project2Tree)).isTrue(); + assertThat(getMySetting(project1Tree)).isTrue(); + assertThat(getMySetting(project2Tree)).isTrue(); // Enable extension setFile("project.git/config").toLines("[core]", "mySetting = true", "[extensions]", "worktreeConfig = true"); - Assertions.assertThat(getMySetting(project1Tree)).isFalse(); // Should now be overridden by config.worktree - Assertions.assertThat(getMySetting(project2Tree)).isTrue(); + assertThat(getMySetting(project1Tree)).isFalse(); // Should now be overridden by config.worktree + assertThat(getMySetting(project2Tree)).isTrue(); } private boolean getMySetting(File projectDir) { diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/cpp/EclipseCdtFormatterStepTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/cpp/EclipseCdtFormatterStepTest.java index 811f811ee0..a0709e86c1 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/cpp/EclipseCdtFormatterStepTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/cpp/EclipseCdtFormatterStepTest.java @@ -28,8 +28,8 @@ public EclipseCdtFormatterStepTest() { super(EclipseCdtFormatterStep.createBuilder(TestProvisioner.mavenCentral())); } - @ParameterizedTest @MethodSource + @ParameterizedTest void formatWithVersion(String version) throws Exception { harnessFor(version).test("main.c", "#include ;\nint main(int argc, \nchar *argv[]) {}", diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepSpecialCaseTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepSpecialCaseTest.java index 25eeb9808c..1380771db3 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepSpecialCaseTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepSpecialCaseTest.java @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.extra.groovy; -import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertThrows; + import org.junit.jupiter.api.Test; import com.diffplug.spotless.StepHarness; @@ -30,7 +31,7 @@ public class GrEclipseFormatterStepSpecialCaseTest { */ @Test public void issue_1657() { - Assertions.assertThrows(RuntimeException.class, () -> StepHarness.forStep(GrEclipseFormatterStep.createBuilder(TestProvisioner.mavenCentral()).build()) + assertThrows(RuntimeException.class, () -> StepHarness.forStep(GrEclipseFormatterStep.createBuilder(TestProvisioner.mavenCentral()).build()) .testResourceUnaffected("groovy/greclipse/format/SomeClass.test")); } diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepTest.java index 6b00c0e794..6afb61feb9 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepTest.java @@ -31,8 +31,8 @@ public GrEclipseFormatterStepTest() { super(GrEclipseFormatterStep.createBuilder(TestProvisioner.mavenCentral())); } - @ParameterizedTest @MethodSource + @ParameterizedTest void formatWithVersion(String version) throws Exception { harnessFor(version).test("test.groovy", "class F{ def m(){} }", "class F{\n\tdef m(){}\n}"); diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/java/EclipseJdtEqualityTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/java/EclipseJdtEqualityTest.java index c842337b3e..458c1afac0 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/java/EclipseJdtEqualityTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/java/EclipseJdtEqualityTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,9 @@ */ package com.diffplug.spotless.extra.java; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -22,7 +25,6 @@ import java.io.Serializable; import java.util.List; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.diffplug.spotless.FormatterStep; @@ -38,12 +40,12 @@ public void test() throws Exception { var step1 = withSettingsFile(settings1); var step2 = withSettingsFile(settings2); - Assertions.assertTrue(step1.equals(step2)); - Assertions.assertTrue(step1.hashCode() == step2.hashCode()); + assertTrue(step1.equals(step2)); + assertTrue(step1.hashCode() == step2.hashCode()); var serialized1 = toBytes(step1); var serialized2 = toBytes(step2); - Assertions.assertFalse(serialized1.equals(serialized2)); + assertFalse(serialized1.equals(serialized2)); } private static FormatterStep withSettingsFile(File settingsFile) { diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/java/EclipseJdtFormatterStepTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/java/EclipseJdtFormatterStepTest.java index dbbfdb04a0..9354d6838e 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/java/EclipseJdtFormatterStepTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/java/EclipseJdtFormatterStepTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,8 @@ public EclipseJdtFormatterStepTest() { super(createBuilder()); } - @ParameterizedTest @MethodSource + @ParameterizedTest void formatWithVersion(String version) throws Exception { harnessFor(version).test("test.java", "package p; class C{}", 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 ea0001d517..6ccecd18e3 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 @@ -46,8 +46,8 @@ public NestedTests(String unformatted, String formatted, EclipseWtpFormatterStep this.formatted = formatted; } - @ParameterizedTest @MethodSource + @ParameterizedTest void formatWithVersion(String version) throws Exception { harnessFor(version).test("someFilename", unformatted, formatted); } 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 abf55ba936..44df59d8ea 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 @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,11 @@ */ package com.diffplug.spotless.glue.java; +import static java.util.Collections.emptyList; + import java.io.File; import java.io.IOException; import java.util.Arrays; -import java.util.Collections; import java.util.List; import org.slf4j.Logger; @@ -48,8 +49,8 @@ public class JavaCleanthatRefactorerFunc implements FormatterFunc.NeedsFile { public JavaCleanthatRefactorerFunc(String jdkVersion, List included, List excluded, boolean includeDraft) { this.jdkVersion = jdkVersion == null ? IJdkVersionConstants.JDK_8 : jdkVersion; - this.included = included == null ? Collections.emptyList() : included; - this.excluded = excluded == null ? Collections.emptyList() : excluded; + this.included = included == null ? emptyList() : included; + this.excluded = excluded == null ? emptyList() : excluded; this.includeDraft = includeDraft; } diff --git a/lib/src/compatDiktat1Dot2Dot5/java/com/diffplug/spotless/glue/diktat/compat/DiktatCompat1Dot2Dot5Adapter.java b/lib/src/compatDiktat1Dot2Dot5/java/com/diffplug/spotless/glue/diktat/compat/DiktatCompat1Dot2Dot5Adapter.java index ff27e96d47..f4f68944ea 100644 --- a/lib/src/compatDiktat1Dot2Dot5/java/com/diffplug/spotless/glue/diktat/compat/DiktatCompat1Dot2Dot5Adapter.java +++ b/lib/src/compatDiktat1Dot2Dot5/java/com/diffplug/spotless/glue/diktat/compat/DiktatCompat1Dot2Dot5Adapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,11 @@ */ package com.diffplug.spotless.glue.diktat.compat; +import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonList; + import java.io.File; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import javax.annotation.Nullable; @@ -41,7 +43,7 @@ public DiktatCompat1Dot2Dot5Adapter(@Nullable File configFile) { if (configFile != null) { System.setProperty("diktat.config.path", configFile.getAbsolutePath()); } - this.ruleSets = Collections.singletonList(new DiktatRuleSetProvider().get()); + this.ruleSets = singletonList(new DiktatRuleSetProvider().get()); this.formatterCallback = new FormatterCallback(errors); } @@ -70,7 +72,7 @@ public String format(final File file, final String content, final boolean isScri file.getAbsolutePath(), content, ruleSets, - Collections.emptyMap(), + emptyMap(), formatterCallback, isScript, null, diff --git a/lib/src/compatDiktat2Dot0Dot0/java/com/diffplug/spotless/glue/diktat/compat/DiktatCompat2Dot0Dot0Adapter.java b/lib/src/compatDiktat2Dot0Dot0/java/com/diffplug/spotless/glue/diktat/compat/DiktatCompat2Dot0Dot0Adapter.java index b0625b82bb..79c19ed299 100644 --- a/lib/src/compatDiktat2Dot0Dot0/java/com/diffplug/spotless/glue/diktat/compat/DiktatCompat2Dot0Dot0Adapter.java +++ b/lib/src/compatDiktat2Dot0Dot0/java/com/diffplug/spotless/glue/diktat/compat/DiktatCompat2Dot0Dot0Adapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,12 +15,13 @@ */ package com.diffplug.spotless.glue.diktat.compat; +import static java.util.Collections.emptyList; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import org.jetbrains.annotations.NotNull; @@ -85,7 +86,7 @@ private static DiktatProcessor getDiktatReporter(File configFile) { private static List readRuleConfigs(File configFile) { if (configFile == null) { - return Collections.emptyList(); + return emptyList(); } try (final InputStream configInputStream = new FileInputStream(configFile)) { return DiktatFactoriesKt.getDiktatRuleConfigReader().invoke(configInputStream); 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 78bd28f86b..1192996b62 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 @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,10 @@ */ package com.diffplug.spotless.glue.ktlint.compat; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static java.util.stream.Collectors.toUnmodifiableSet; + import java.nio.file.Files; import java.nio.file.Path; import java.util.List; @@ -22,7 +26,6 @@ import java.util.Objects; import java.util.ServiceLoader; import java.util.Set; -import java.util.stream.Collectors; import java.util.stream.Stream; import com.pinterest.ktlint.core.KtLintRuleEngine; @@ -83,7 +86,7 @@ public String format( Set allRuleProviders = ServiceLoader.load(RuleSetProviderV2.class, RuleSetProviderV2.class.getClassLoader()) .stream() .flatMap(loader -> loader.get().getRuleProviders().stream()) - .collect(Collectors.toUnmodifiableSet()); + .collect(toUnmodifiableSet()); EditorConfigOverride editorConfigOverride; if (editorConfigOverrideMap.isEmpty()) { @@ -91,7 +94,7 @@ public String format( } else { editorConfigOverride = createEditorConfigOverride(allRuleProviders.stream().map( RuleProvider::createNewRuleInstance).collect( - Collectors.toList()), + toList()), editorConfigOverrideMap); } EditorConfigDefaults editorConfig; @@ -122,7 +125,7 @@ private static EditorConfigOverride createEditorConfigOverride(final List Map> supportedProperties = Stream .concat(ruleProperties, DEFAULT_EDITOR_CONFIG_PROPERTIES.stream()) .distinct() - .collect(Collectors.toMap(EditorConfigProperty::getName, property -> property)); + .collect(toMap(EditorConfigProperty::getName, property -> property)); // Create config properties based on provided property names and values @SuppressWarnings("unchecked") diff --git a/lib/src/compatKtLint0Dot49Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot49Dot0Adapter.java b/lib/src/compatKtLint0Dot49Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot49Dot0Adapter.java index f4c1e04af7..abca0ae6d0 100644 --- a/lib/src/compatKtLint0Dot49Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot49Dot0Adapter.java +++ b/lib/src/compatKtLint0Dot49Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot49Dot0Adapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,10 @@ */ package com.diffplug.spotless.glue.ktlint.compat; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static java.util.stream.Collectors.toUnmodifiableSet; + import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.Files; @@ -24,7 +28,6 @@ import java.util.Objects; import java.util.ServiceLoader; import java.util.Set; -import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; @@ -130,14 +133,14 @@ public String format( Set allRuleProviders = ServiceLoader.load(RuleSetProviderV3.class, RuleSetProviderV3.class.getClassLoader()) .stream() .flatMap(loader -> loader.get().getRuleProviders().stream()) - .collect(Collectors.toUnmodifiableSet()); + .collect(toUnmodifiableSet()); EditorConfigOverride editorConfigOverride; if (editorConfigOverrideMap.isEmpty()) { editorConfigOverride = EditorConfigOverride.Companion.getEMPTY_EDITOR_CONFIG_OVERRIDE(); } else { editorConfigOverride = createEditorConfigOverride(allRuleProviders.stream().map( - RuleProvider::createNewRuleInstance).collect(Collectors.toList()), + RuleProvider::createNewRuleInstance).collect(toList()), editorConfigOverrideMap); } EditorConfigDefaults editorConfig; @@ -171,7 +174,7 @@ private static EditorConfigOverride createEditorConfigOverride(final List Map> supportedProperties = Stream .concat(ruleProperties, DEFAULT_EDITOR_CONFIG_PROPERTIES.stream()) .distinct() - .collect(Collectors.toMap(EditorConfigProperty::getName, property -> property)); + .collect(toMap(EditorConfigProperty::getName, property -> property)); // Create config properties based on provided property names and values @SuppressWarnings("unchecked") diff --git a/lib/src/compatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0Adapter.java b/lib/src/compatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0Adapter.java index 951b82704a..79d96df853 100644 --- a/lib/src/compatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0Adapter.java +++ b/lib/src/compatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0Adapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,10 @@ */ package com.diffplug.spotless.glue.ktlint.compat; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static java.util.stream.Collectors.toUnmodifiableSet; + import java.nio.file.Files; import java.nio.file.Path; import java.util.List; @@ -22,7 +26,6 @@ import java.util.Objects; import java.util.ServiceLoader; import java.util.Set; -import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; @@ -92,14 +95,14 @@ public String format( Set allRuleProviders = ServiceLoader.load(RuleSetProviderV3.class, RuleSetProviderV3.class.getClassLoader()) .stream() .flatMap(loader -> loader.get().getRuleProviders().stream()) - .collect(Collectors.toUnmodifiableSet()); + .collect(toUnmodifiableSet()); EditorConfigOverride editorConfigOverride; if (editorConfigOverrideMap.isEmpty()) { editorConfigOverride = EditorConfigOverride.Companion.getEMPTY_EDITOR_CONFIG_OVERRIDE(); } else { editorConfigOverride = createEditorConfigOverride(allRuleProviders.stream().map( - RuleProvider::createNewRuleInstance).collect(Collectors.toList()), + RuleProvider::createNewRuleInstance).collect(toList()), editorConfigOverrideMap); } EditorConfigDefaults editorConfig; @@ -134,7 +137,7 @@ private static EditorConfigOverride createEditorConfigOverride(final List Map> supportedProperties = Stream .concat(ruleProperties, DEFAULT_EDITOR_CONFIG_PROPERTIES.stream()) .distinct() - .collect(Collectors.toMap(EditorConfigProperty::getName, property -> property)); + .collect(toMap(EditorConfigProperty::getName, property -> property)); // Create config properties based on provided property names and values @SuppressWarnings("unchecked") diff --git a/lib/src/compatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0Adapter.java b/lib/src/compatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0Adapter.java index 86387d0d6b..9a19bd4e39 100644 --- a/lib/src/compatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0Adapter.java +++ b/lib/src/compatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0Adapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,16 @@ */ package com.diffplug.spotless.glue.ktlint.compat; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static java.util.stream.Collectors.toUnmodifiableSet; + import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.ServiceLoader; import java.util.Set; -import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; @@ -91,7 +94,7 @@ public String format( Set allRuleProviders = ServiceLoader.load(RuleSetProviderV3.class, RuleSetProviderV3.class.getClassLoader()) .stream() .flatMap(loader -> loader.get().getRuleProviders().stream()) - .collect(Collectors.toUnmodifiableSet()); + .collect(toUnmodifiableSet()); EditorConfigDefaults editorConfig = EditorConfigDefaults.Companion.load(editorConfigPath, RuleProviderKt.propertyTypes(allRuleProviders)); EditorConfigOverride editorConfigOverride; @@ -100,7 +103,7 @@ public String format( } else { editorConfigOverride = createEditorConfigOverride( editorConfig, - allRuleProviders.stream().map(RuleProvider::createNewRuleInstance).collect(Collectors.toList()), + allRuleProviders.stream().map(RuleProvider::createNewRuleInstance).collect(toList()), editorConfigOverrideMap); } @@ -128,7 +131,7 @@ private static EditorConfigOverride createEditorConfigOverride(final EditorConfi Map> supportedProperties = Stream .concat(ruleProperties, DEFAULT_EDITOR_CONFIG_PROPERTIES.stream()) .distinct() - .collect(Collectors.toMap(EditorConfigProperty::getName, property -> property)); + .collect(toMap(EditorConfigProperty::getName, property -> property)); // The default style had been changed from intellij_idea to ktlint_official in version 1.0.0 boolean isCodeStyleDefinedInEditorConfig = editorConfig.getValue().getSections().stream() 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 700c84da45..87da310a65 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-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,9 @@ */ package com.diffplug.spotless.glue.diktat; +import static java.util.stream.Collectors.toList; + import java.io.File; -import java.util.stream.Collectors; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.Lint; @@ -46,7 +47,7 @@ public String applyWithFile(String unix, File file) { try { return adapter.format(file, unix, isScript); } catch (DiktatReporting.LintException e) { - throw Lint.shortcut(e.lints.stream().map(lint -> Lint.atLine(lint.line, lint.ruleId, lint.detail)).collect(Collectors.toList())); + throw Lint.shortcut(e.lints.stream().map(lint -> Lint.atLine(lint.line, lint.ruleId, lint.detail)).collect(toList())); } } } diff --git a/lib/src/googleJavaFormat/java/com/diffplug/spotless/glue/java/GoogleJavaFormatFormatterFunc.java b/lib/src/googleJavaFormat/java/com/diffplug/spotless/glue/java/GoogleJavaFormatFormatterFunc.java index d13f8d9d40..1d64aa922a 100644 --- a/lib/src/googleJavaFormat/java/com/diffplug/spotless/glue/java/GoogleJavaFormatFormatterFunc.java +++ b/lib/src/googleJavaFormat/java/com/diffplug/spotless/glue/java/GoogleJavaFormatFormatterFunc.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package com.diffplug.spotless.glue.java; -import java.util.Objects; +import static java.util.Objects.requireNonNull; import javax.annotation.Nonnull; @@ -47,8 +47,8 @@ public class GoogleJavaFormatFormatterFunc implements FormatterFunc { private final boolean reorderImports; public GoogleJavaFormatFormatterFunc(@Nonnull String version, @Nonnull String style, boolean reflowStrings, boolean reorderImports, boolean formatJavadoc) { - this.version = Objects.requireNonNull(version); - this.formatterStyle = Style.valueOf(Objects.requireNonNull(style)); + this.version = requireNonNull(version); + this.formatterStyle = Style.valueOf(requireNonNull(style)); this.reflowStrings = reflowStrings; this.reorderImports = reorderImports; @@ -59,8 +59,8 @@ public GoogleJavaFormatFormatterFunc(@Nonnull String version, @Nonnull String st this.formatter = new Formatter(builder.build()); } - @Override @Nonnull + @Override public String apply(@Nonnull String input) throws Exception { String formatted = formatter.formatSource(input); String removedUnused = RemoveUnusedImports.removeUnusedImports(formatted); diff --git a/lib/src/googleJavaFormat/java/com/diffplug/spotless/glue/java/GoogleJavaFormatRemoveUnusedImporterFormatterFunc.java b/lib/src/googleJavaFormat/java/com/diffplug/spotless/glue/java/GoogleJavaFormatRemoveUnusedImporterFormatterFunc.java index de21a18795..6ad1decf0f 100644 --- a/lib/src/googleJavaFormat/java/com/diffplug/spotless/glue/java/GoogleJavaFormatRemoveUnusedImporterFormatterFunc.java +++ b/lib/src/googleJavaFormat/java/com/diffplug/spotless/glue/java/GoogleJavaFormatRemoveUnusedImporterFormatterFunc.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package com.diffplug.spotless.glue.java; -import java.util.Objects; +import static java.util.Objects.requireNonNull; import javax.annotation.Nonnull; @@ -29,11 +29,11 @@ public class GoogleJavaFormatRemoveUnusedImporterFormatterFunc implements Format private final String version; public GoogleJavaFormatRemoveUnusedImporterFormatterFunc(@Nonnull String version) { - this.version = Objects.requireNonNull(version); + this.version = requireNonNull(version); } - @Override @Nonnull + @Override public String apply(@Nonnull String input) throws Exception { return RemoveUnusedImports.removeUnusedImports(input); } 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..d9cd1c5fde 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 @@ -1,5 +1,5 @@ /* - * Copyright 2021-2023 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,6 +43,7 @@ public JacksonYamlFormatterFunc(JacksonYamlConfig jacksonConfig) { } } + @Override protected JsonFactory makeJsonFactory() { YAMLFactoryBuilder yamlFactoryBuilder = new YAMLFactoryBuilder(new YAMLFactory()); diff --git a/lib/src/main/java/com/diffplug/spotless/DelegateFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/DelegateFormatterStep.java index 18d64b4759..02871784b7 100644 --- a/lib/src/main/java/com/diffplug/spotless/DelegateFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/DelegateFormatterStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2022-2024 DiffPlug + * Copyright 2022-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,14 +15,14 @@ */ package com.diffplug.spotless; -import java.util.Objects; +import static java.util.Objects.requireNonNull; /** Superclass of all compound FormatterSteps necessary for {@link com.diffplug.spotless.LazyForwardingEquality#unlazy(java.lang.Object)}. */ abstract class DelegateFormatterStep implements FormatterStep { protected final FormatterStep delegateStep; DelegateFormatterStep(FormatterStep delegateStep) { - this.delegateStep = Objects.requireNonNull(delegateStep); + this.delegateStep = requireNonNull(delegateStep); } @Override diff --git a/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java b/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java index a7d5e1e478..e056ef9f1c 100644 --- a/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java +++ b/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java @@ -15,13 +15,15 @@ */ package com.diffplug.spotless; +import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.nio.charset.StandardCharsets.UTF_8; + 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; import java.util.Collection; import java.util.Iterator; @@ -67,7 +69,7 @@ private EncodingErrorMsg(String chars, ByteBuffer byteBuf, Charset charset, int charBuf = CharBuffer.allocate(Math.min(unrepresentable + 2 * CONTEXT, chars.length())); message = new StringBuilder("Encoding error! "); - if (charset.equals(StandardCharsets.UTF_8)) { + if (charset.equals(UTF_8)) { message.append("Spotless uses UTF-8 by default."); } else { message.append("You configured Spotless to use ").append(charset.name()).append("."); @@ -89,9 +91,9 @@ private EncodingErrorMsg(String chars, ByteBuffer byteBuf, Charset charset, int // https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html LinkedHashSet encodings = new LinkedHashSet<>(); encodings.add(charset); // the encoding we are using - encodings.add(StandardCharsets.UTF_8); // followed by likely encodings + encodings.add(UTF_8); // followed by likely encodings addIfAvailable(encodings, "windows-1252"); - encodings.add(StandardCharsets.ISO_8859_1); + encodings.add(ISO_8859_1); addIfAvailable(encodings, "Shift_JIS"); addIfAvailable(encodings, "Big5"); addIfAvailable(encodings, "Big5-HKSCS"); diff --git a/lib/src/main/java/com/diffplug/spotless/FeatureClassLoader.java b/lib/src/main/java/com/diffplug/spotless/FeatureClassLoader.java index 0eb5aa4d2e..e9f95374c4 100644 --- a/lib/src/main/java/com/diffplug/spotless/FeatureClassLoader.java +++ b/lib/src/main/java/com/diffplug/spotless/FeatureClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,8 @@ */ package com.diffplug.spotless; +import static java.util.Objects.requireNonNull; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -22,7 +24,6 @@ import java.net.URLClassLoader; import java.nio.ByteBuffer; import java.security.ProtectionDomain; -import java.util.Objects; /** * This class loader is used to load classes of Spotless features from a search @@ -56,7 +57,7 @@ class FeatureClassLoader extends URLClassLoader { */ FeatureClassLoader(URL[] urls, ClassLoader buildToolClassLoader) { super(urls, getParentClassLoader()); - Objects.requireNonNull(buildToolClassLoader); + requireNonNull(buildToolClassLoader); this.buildToolClassLoader = buildToolClassLoader; } diff --git a/lib/src/main/java/com/diffplug/spotless/FileSignature.java b/lib/src/main/java/com/diffplug/spotless/FileSignature.java index f0332aef1f..1204fbb521 100644 --- a/lib/src/main/java/com/diffplug/spotless/FileSignature.java +++ b/lib/src/main/java/com/diffplug/spotless/FileSignature.java @@ -17,6 +17,7 @@ import static com.diffplug.spotless.MoreIterables.toNullHostileList; import static com.diffplug.spotless.MoreIterables.toSortedSet; +import static java.util.Collections.unmodifiableList; import static java.util.Comparator.comparing; import java.io.File; @@ -28,7 +29,6 @@ import java.security.MessageDigest; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; @@ -103,8 +103,7 @@ public static final class Promised implements Serializable { @Serial private static final long serialVersionUID = 1L; private final List files; - @SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") - private transient @Nullable FileSignature cached; + @Nullable private transient @SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") FileSignature cached; private Promised(List files, @Nullable FileSignature cached) { this.files = files; @@ -134,7 +133,7 @@ public static Promised promise(File file) { /** Returns all of the files in this signature, throwing an exception if there are more or less than 1 file. */ public Collection files() { - return Collections.unmodifiableList(files); + return unmodifiableList(files); } /** Returns the only file in this signature, throwing an exception if there are more or less than 1 file. */ diff --git a/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java index 9041bdb6c5..783346ae05 100644 --- a/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.Serial; import java.util.List; @@ -30,13 +32,12 @@ final class FilterByContentPatternFormatterStep extends DelegateFormatterStep { FilterByContentPatternFormatterStep(FormatterStep delegateStep, OnMatch onMatch, String contentPattern) { super(delegateStep); this.onMatch = onMatch; - this.contentPattern = Pattern.compile(Objects.requireNonNull(contentPattern)); + this.contentPattern = Pattern.compile(requireNonNull(contentPattern)); } - @Override - public @Nullable String format(String raw, File file) throws Exception { - Objects.requireNonNull(raw, "raw"); - Objects.requireNonNull(file, "file"); + @Nullable public @Override String format(String raw, File file) throws Exception { + requireNonNull(raw, "raw"); + requireNonNull(file, "file"); if (contentPattern.matcher(raw).find() == (onMatch == OnMatch.INCLUDE)) { return delegateStep.format(raw, file); } else { @@ -46,8 +47,8 @@ final class FilterByContentPatternFormatterStep extends DelegateFormatterStep { @Override public List lint(String raw, File file) throws Exception { - Objects.requireNonNull(raw, "raw"); - Objects.requireNonNull(file, "file"); + requireNonNull(raw, "raw"); + requireNonNull(file, "file"); if (contentPattern.matcher(raw).find() == (onMatch == OnMatch.INCLUDE)) { return delegateStep.lint(raw, file); } else { diff --git a/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java index 7de0a32fbc..43a46e97fc 100644 --- a/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.Serial; import java.util.List; @@ -27,13 +29,12 @@ final class FilterByFileFormatterStep extends DelegateFormatterStep { FilterByFileFormatterStep(FormatterStep delegateStep, SerializableFileFilter filter) { super(delegateStep); - this.filter = Objects.requireNonNull(filter); + this.filter = requireNonNull(filter); } - @Override - public @Nullable String format(String raw, File file) throws Exception { - Objects.requireNonNull(raw, "raw"); - Objects.requireNonNull(file, "file"); + @Nullable public @Override String format(String raw, File file) throws Exception { + requireNonNull(raw, "raw"); + requireNonNull(file, "file"); if (filter.accept(file)) { return delegateStep.format(raw, file); } else { @@ -43,8 +44,8 @@ final class FilterByFileFormatterStep extends DelegateFormatterStep { @Override public List lint(String content, File file) throws Exception { - Objects.requireNonNull(content, "content"); - Objects.requireNonNull(file, "file"); + requireNonNull(content, "content"); + requireNonNull(file, "file"); if (filter.accept(file)) { return delegateStep.lint(content, file); } else { diff --git a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java index d205e14039..9d74f02544 100644 --- a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java +++ b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java @@ -15,11 +15,12 @@ */ package com.diffplug.spotless; +import static java.util.Objects.requireNonNull; + import java.io.IOException; import java.io.Serial; import java.io.Serializable; import java.nio.charset.Charset; -import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -49,20 +50,20 @@ public class ForeignExe implements Serializable { /** The name of the executable, used by "where" (win) and "which" (unix). */ public static ForeignExe nameAndVersion(String exeName, String version) { ForeignExe foreign = new ForeignExe(); - foreign.name = Objects.requireNonNull(exeName); - foreign.version = Objects.requireNonNull(version); + foreign.name = requireNonNull(exeName); + foreign.version = requireNonNull(version); return foreign; } /** The flag which causes the exe to print its version (defaults to --version). */ public ForeignExe versionFlag(String versionFlag) { - this.versionFlag = Objects.requireNonNull(versionFlag); + this.versionFlag = requireNonNull(versionFlag); return this; } /** A regex which can parse the version out of the output of the {@link #versionFlag(String)} command (defaults to {@code version (\\S*)}) */ public ForeignExe versionRegex(Pattern versionRegex) { - this.versionRegex = Objects.requireNonNull(versionRegex); + this.versionRegex = requireNonNull(versionRegex); return this; } @@ -134,7 +135,7 @@ private RuntimeException exceptionFmt(String msgPrimary, ProcessRunner.Result cm errorMsg.append(msgFix); errorMsg.append('\n'); } - errorMsg.append(cmd.toString()); + errorMsg.append(cmd); return new RuntimeException(errorMsg.toString()); } } diff --git a/lib/src/main/java/com/diffplug/spotless/Formatter.java b/lib/src/main/java/com/diffplug/spotless/Formatter.java index 941667adb4..f001636ea8 100644 --- a/lib/src/main/java/com/diffplug/spotless/Formatter.java +++ b/lib/src/main/java/com/diffplug/spotless/Formatter.java @@ -16,6 +16,7 @@ package com.diffplug.spotless; import static com.diffplug.spotless.LibPreconditions.requireElementsNonNull; +import static java.util.Objects.requireNonNull; import java.io.File; import java.io.IOException; @@ -27,7 +28,6 @@ import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,8 +44,8 @@ public final class Formatter implements Serializable, AutoCloseable { private List steps; private Formatter(LineEnding.Policy lineEndingsPolicy, Charset encoding, List steps) { - this.lineEndingsPolicy = Objects.requireNonNull(lineEndingsPolicy, "lineEndingsPolicy"); - this.encoding = Objects.requireNonNull(encoding, "encoding"); + this.lineEndingsPolicy = requireNonNull(lineEndingsPolicy, "lineEndingsPolicy"); + this.encoding = requireNonNull(encoding, "encoding"); this.steps = requireElementsNonNull(new ArrayList<>(steps)); } @@ -116,8 +116,8 @@ public Formatter build() { /** Applies the appropriate line endings to the given unix content. */ public String computeLineEndings(String unix, File file) { - Objects.requireNonNull(unix, "unix"); - Objects.requireNonNull(file, "file"); + requireNonNull(unix, "unix"); + requireNonNull(file, "file"); String ending = lineEndingsPolicy.getEndingFor(file); if (!ending.equals(LineEnding.UNIX.str())) { @@ -162,8 +162,8 @@ static void legacyErrorBehavior(Formatter formatter, File file, ValuePerStep exceptionPerStep) { - Objects.requireNonNull(unix, "unix"); - Objects.requireNonNull(file, "file"); + requireNonNull(unix, "unix"); + requireNonNull(file, "file"); for (int i = 0; i < steps.size(); i++) { FormatterStep step = steps.get(i); @@ -220,8 +220,8 @@ public boolean equals(Object obj) { && steps.equals(other.steps); } - @SuppressWarnings("rawtypes") @Override + @SuppressWarnings("rawtypes") public void close() { for (FormatterStep step : steps) { try { diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterFunc.java b/lib/src/main/java/com/diffplug/spotless/FormatterFunc.java index 5e6c44b335..0b80ccc6de 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatterFunc.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatterFunc.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,10 @@ */ package com.diffplug.spotless; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.util.List; -import java.util.Objects; /** * A {@code Function} which can throw an exception. Technically, there @@ -60,8 +61,8 @@ interface Closeable extends FormatterFunc, AutoCloseable { * How the {@code of()} methods below make the correct thing easier to write and safer: https://github.com/diffplug/spotless/commit/18c10f9c93d6f18f753233d0b5f028d5f0961916 */ public static Closeable ofDangerous(AutoCloseable closeable, FormatterFunc function) { - Objects.requireNonNull(closeable, "closeable"); - Objects.requireNonNull(function, "function"); + requireNonNull(closeable, "closeable"); + requireNonNull(function, "function"); return new Closeable() { @Override public void close() { @@ -95,8 +96,8 @@ default List lint(T resource, String unix) throws Exception { /** Creates a {@link FormatterFunc.Closeable} which uses the given resource to execute the format function. */ public static Closeable of(T resource, ResourceFunc function) { - Objects.requireNonNull(resource, "resource"); - Objects.requireNonNull(function, "function"); + requireNonNull(resource, "resource"); + requireNonNull(function, "function"); return new Closeable() { @Override public void close() { @@ -126,8 +127,8 @@ default List lint(T resource, String content, File file) throws Exception /** Creates a {@link FormatterFunc.Closeable} which uses the given resource to execute the file-dependent format function. */ public static Closeable of(T resource, ResourceFuncNeedsFile function) { - Objects.requireNonNull(resource, "resource"); - Objects.requireNonNull(function, "function"); + requireNonNull(resource, "resource"); + requireNonNull(function, "function"); return new Closeable() { @Override public void close() { diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java b/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java index 0aaf1daea5..0696bb4fa5 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java @@ -16,6 +16,10 @@ package com.diffplug.spotless; import static com.diffplug.spotless.MoreIterables.toNullHostileList; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toCollection; import java.io.ByteArrayInputStream; import java.io.File; @@ -23,14 +27,11 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.LinkedList; import java.util.List; -import java.util.Objects; import java.util.Properties; import java.util.function.Supplier; -import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.xml.XMLConstants; @@ -61,7 +62,7 @@ private FormatterProperties() { * In case the import of a file fails */ public static FormatterProperties from(File... files) throws IllegalArgumentException { - Objects.requireNonNull(files); + requireNonNull(files); return from(Arrays.asList(files)); } @@ -84,7 +85,7 @@ public static FormatterProperties fromPropertiesContent(Iterable content List nonNullElements = toNullHostileList(content); FormatterProperties properties = new FormatterProperties(); nonNullElements.forEach(contentElement -> { - try (InputStream is = new ByteArrayInputStream(contentElement.getBytes(StandardCharsets.UTF_8))) { + try (InputStream is = new ByteArrayInputStream(contentElement.getBytes(UTF_8))) { properties.properties.load(is); } catch (IOException e) { throw new IllegalArgumentException("Unable to load properties: " + contentElement); @@ -128,7 +129,7 @@ public static FormatterProperties merge(Properties... properties) { * In case the import of the file fails */ private void add(final File settingsFile) throws IllegalArgumentException { - Objects.requireNonNull(settingsFile); + requireNonNull(settingsFile); if (!(settingsFile.isFile() && settingsFile.canRead())) { String msg = "Settings file '%s' does not exist or can not be read.".formatted(settingsFile); throw new IllegalArgumentException(msg); @@ -182,7 +183,7 @@ protected Properties execute(final File file) throws IOException, IllegalArgumen @Override protected Properties executeXmlContent(String content) throws IOException, IllegalArgumentException { - return executeWithSupplier(() -> new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))); + return executeWithSupplier(() -> new ByteArrayInputStream(content.getBytes(UTF_8))); } private Properties executeWithSupplier(Supplier isSupplier) throws IOException, IllegalArgumentException { @@ -313,7 +314,7 @@ private Node getSingleProfile(final Node rootNode) throws IllegalArgumentExcepti } if (profiles.size() > 1) { String message = "Formatter configuration file contains multiple profiles: ["; - message += profiles.stream().map(XmlParser::getProfileName).collect(Collectors.joining("; ")); + message += profiles.stream().map(XmlParser::getProfileName).collect(joining("; ")); message += "]%n The formatter can only cope with a single profile per configuration file. Please remove the other profiles."; throw new IllegalArgumentException(message); } @@ -325,7 +326,7 @@ private List getChildren(final Node node, final String nodeName) { return IntStream.range(0, children.getLength()) .mapToObj(children::item) .filter(child -> child.getNodeName().equals(nodeName)) - .collect(Collectors.toCollection(LinkedList::new)); + .collect(toCollection(LinkedList::new)); } }; diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterStep.java b/lib/src/main/java/com/diffplug/spotless/FormatterStep.java index a26ade4a41..4530de5fa1 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatterStep.java @@ -15,10 +15,11 @@ */ package com.diffplug.spotless; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.Serializable; import java.util.List; -import java.util.Objects; import javax.annotation.Nullable; @@ -44,8 +45,7 @@ public interface FormatterStep extends Serializable, AutoCloseable { * if the formatter step doesn't have any changes to make * @throws Exception if the formatter step experiences a problem */ - @Nullable - String format(String rawUnix, File file) throws Exception; + @Nullable String format(String rawUnix, File file) throws Exception; /** * Returns a list of lints against the given file content @@ -58,8 +58,7 @@ public interface FormatterStep extends Serializable, AutoCloseable { * @return a list of lints * @throws Exception if the formatter step experiences a problem */ - @Nullable - default List lint(String content, File file) throws Exception { + @Nullable default List lint(String content, File file) throws Exception { return List.of(); } @@ -164,7 +163,7 @@ static FormatterStep create( String name, State state, SerializedFunction stateToFormatter) { - Objects.requireNonNull(state, "state"); + requireNonNull(state, "state"); return createLazy(name, () -> state, stateToFormatter); } } diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterStepSerializationRoundtrip.java b/lib/src/main/java/com/diffplug/spotless/FormatterStepSerializationRoundtrip.java index 15febb27ff..57488e1ba8 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatterStepSerializationRoundtrip.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatterStepSerializationRoundtrip.java @@ -15,11 +15,12 @@ */ package com.diffplug.spotless; +import static java.util.Objects.requireNonNull; + import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serial; import java.io.Serializable; -import java.util.Objects; import edu.umd.cs.findbugs.annotations.Nullable; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -122,7 +123,7 @@ private void writeObject(ObjectOutputStream out) throws IOException { } public FormatterStep rehydrate() { - return original != null ? original : Objects.requireNonNull(cleaned, "how is clean null if this has been serialized?"); + return original != null ? original : requireNonNull(cleaned, "how is clean null if this has been serialized?"); } @Override diff --git a/lib/src/main/java/com/diffplug/spotless/JarState.java b/lib/src/main/java/com/diffplug/spotless/JarState.java index 9f04c721ae..d5f5a21851 100644 --- a/lib/src/main/java/com/diffplug/spotless/JarState.java +++ b/lib/src/main/java/com/diffplug/spotless/JarState.java @@ -15,6 +15,9 @@ */ package com.diffplug.spotless; +import static java.util.Collections.singletonList; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; @@ -25,7 +28,6 @@ import java.net.URI; import java.net.URL; import java.util.Collection; -import java.util.Collections; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Set; @@ -113,7 +115,7 @@ private JarState(FileSignature fileSignature) { /** Provisions the given maven coordinate and its transitive dependencies. */ public static JarState from(String mavenCoordinate, Provisioner provisioner) throws IOException { - return from(Collections.singletonList(mavenCoordinate), provisioner); + return from(singletonList(mavenCoordinate), provisioner); } /** Provisions the given maven coordinates and their transitive dependencies. */ @@ -127,8 +129,8 @@ public static JarState withoutTransitives(Collection mavenCoordinates, P } private static JarState provisionWithTransitives(boolean withTransitives, Collection mavenCoordinates, Provisioner provisioner) throws IOException { - Objects.requireNonNull(mavenCoordinates, "mavenCoordinates"); - Objects.requireNonNull(provisioner, "provisioner"); + requireNonNull(mavenCoordinates, "mavenCoordinates"); + requireNonNull(provisioner, "provisioner"); Set jars = provisioner.provisionWithTransitives(withTransitives, mavenCoordinates); if (jars.isEmpty()) { throw new NoSuchElementException("Resolved to an empty result: " + String.join(", ", mavenCoordinates)); diff --git a/lib/src/main/java/com/diffplug/spotless/Jvm.java b/lib/src/main/java/com/diffplug/spotless/Jvm.java index 7d8812546b..75cd2695bb 100644 --- a/lib/src/main/java/com/diffplug/spotless/Jvm.java +++ b/lib/src/main/java/com/diffplug/spotless/Jvm.java @@ -15,17 +15,18 @@ */ package com.diffplug.spotless; +import static java.util.Objects.requireNonNull; +import static java.util.stream.Collectors.joining; + import java.io.File; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; 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; import javax.annotation.Nullable; @@ -88,7 +89,7 @@ private Support(String formatterName, Comparator formatterVersionComp * @return this */ public Support add(int minimumJvmVersion, V maxFormatterVersion) { - Objects.requireNonNull(maxFormatterVersion); + requireNonNull(maxFormatterVersion); if (jvm2fmtMaxVersion.put(minimumJvmVersion, maxFormatterVersion) != null) { throw new IllegalArgumentException("Added duplicate entry for JVM %d+.".formatted(minimumJvmVersion)); } @@ -100,7 +101,7 @@ public Support add(int minimumJvmVersion, V maxFormatterVersion) { } public Support addMin(int minimumJvmVersion, V minFormatterVersion) { - Objects.requireNonNull(minFormatterVersion); + requireNonNull(minFormatterVersion); if (jvm2fmtMinVersion.put(minimumJvmVersion, minFormatterVersion) != null) { throw new IllegalArgumentException("Added duplicate entry for JVM %d+.".formatted(minimumJvmVersion)); } @@ -136,7 +137,7 @@ private void verifyVersionRangesDoNotIntersect(NavigableMap jvm2fmtV * @throws IllegalArgumentException if {@code formatterVersion} not supported */ public void assertFormatterSupported(V formatterVersion) { - Objects.requireNonNull(formatterVersion); + requireNonNull(formatterVersion); String error = buildUnsupportedFormatterMessage(formatterVersion); if (!error.isEmpty()) { throw Lint.atUndefinedLine(LINT_CODE, error).shortcut(); @@ -195,8 +196,8 @@ private int getRequiredJvmVersion(V fmtVersion) { * @return Wrapped formatter function. Adding hint about later versions to exceptions. */ public FormatterFunc suggestLaterVersionOnError(V formatterVersion, FormatterFunc originalFunc) { - Objects.requireNonNull(formatterVersion); - Objects.requireNonNull(originalFunc); + requireNonNull(formatterVersion); + requireNonNull(originalFunc); final String hintUnsupportedProblem = buildUnsupportedFormatterMessage(formatterVersion); final String proposeDifferentFormatter = hintUnsupportedProblem.isEmpty() ? buildUpgradeFormatterMessage(formatterVersion) : hintUnsupportedProblem; return proposeDifferentFormatter.isEmpty() ? originalFunc : new FormatterFunc() { @@ -253,7 +254,7 @@ private String buildUpgradeFormatterMessage(V fmtVersion) { public String toString() { return "%s alternatives:%n".formatted(fmtName) + jvm2fmtMaxVersion.entrySet().stream().map( - e -> "- Version %s requires JVM %d+".formatted(e.getValue(), e.getKey())).collect(Collectors.joining(System.lineSeparator())); + e -> "- Version %s requires JVM %d+".formatted(e.getValue(), e.getKey())).collect(joining(System.lineSeparator())); } @SuppressFBWarnings("SE_COMPARATOR_SHOULD_BE_SERIALIZABLE") @@ -261,8 +262,8 @@ private static class SemanticVersionComparator implements Comparator { @Override public int compare(V version0, V version1) { - Objects.requireNonNull(version0); - Objects.requireNonNull(version1); + requireNonNull(version0); + requireNonNull(version1); int[] version0Items = convert(version0); int[] version1Items = convert(version1); int numberOfElements = version0Items.length > version1Items.length ? version0Items.length : version1Items.length; @@ -299,7 +300,7 @@ private static int[] convert(V versionObject) { * @return Empty map of supported formatters */ public static Support support(String formatterName) { - Objects.requireNonNull(formatterName); + requireNonNull(formatterName); return new Support<>(formatterName); } diff --git a/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java b/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java index 443deb7ac3..46cb5cebf5 100644 --- a/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java +++ b/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless; +import static java.util.Objects.requireNonNull; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -24,7 +26,6 @@ import java.io.Serial; import java.io.Serializable; import java.util.Arrays; -import java.util.Objects; import javax.annotation.Nullable; @@ -73,7 +74,7 @@ private void writeObject(ObjectOutputStream out) throws IOException { // override serialize input @SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - state = (T) Objects.requireNonNull(in.readObject()); + state = (T) requireNonNull(in.readObject()); } // override serialize input diff --git a/lib/src/main/java/com/diffplug/spotless/LibPreconditions.java b/lib/src/main/java/com/diffplug/spotless/LibPreconditions.java index 635a0c724a..e09b46ff4c 100644 --- a/lib/src/main/java/com/diffplug/spotless/LibPreconditions.java +++ b/lib/src/main/java/com/diffplug/spotless/LibPreconditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,16 +15,16 @@ */ package com.diffplug.spotless; -import java.util.Objects; +import static java.util.Objects.requireNonNull; final class LibPreconditions { // prevent direct instantiation private LibPreconditions() {} static > I requireElementsNonNull(I elements) { - Objects.requireNonNull(elements); + requireNonNull(elements); for (Object element : elements) { - Objects.requireNonNull(element); + requireNonNull(element); } return elements; } diff --git a/lib/src/main/java/com/diffplug/spotless/LineEnding.java b/lib/src/main/java/com/diffplug/spotless/LineEnding.java index 225ba7b63a..6840e9547b 100644 --- a/lib/src/main/java/com/diffplug/spotless/LineEnding.java +++ b/lib/src/main/java/com/diffplug/spotless/LineEnding.java @@ -15,6 +15,9 @@ */ package com.diffplug.spotless; +import static java.nio.charset.StandardCharsets.US_ASCII; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -22,8 +25,6 @@ import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Method; -import java.nio.charset.StandardCharsets; -import java.util.Objects; import java.util.function.Supplier; /** @@ -34,7 +35,7 @@ public enum LineEnding { /** Uses the same line endings as Git, using {@code .gitattributes} and the {@code core.eol} property. */ GIT_ATTRIBUTES { /** .gitattributes is path-specific, so you must use {@link LineEnding#createPolicy(File, Supplier)}. */ - @Override @Deprecated + @Deprecated @Override public Policy createPolicy() { return super.createPolicy(); } @@ -42,7 +43,7 @@ public Policy createPolicy() { /** Uses the same line endings as Git, and assumes that every single file being formatted will have the same line ending. */ GIT_ATTRIBUTES_FAST_ALLSAME { /** .gitattributes is path-specific, so you must use {@link LineEnding#createPolicy(File, Supplier)}. */ - @Override @Deprecated + @Deprecated @Override public Policy createPolicy() { return super.createPolicy(); } @@ -61,8 +62,8 @@ public Policy createPolicy() { /** Returns a {@link Policy} appropriate for files which are contained within the given rootFolder. */ public Policy createPolicy(File projectDir, Supplier> toFormat) { - Objects.requireNonNull(projectDir, "projectDir"); - Objects.requireNonNull(toFormat, "toFormat"); + requireNonNull(projectDir, "projectDir"); + requireNonNull(toFormat, "toFormat"); String gitAttributesMethod; if (this == GIT_ATTRIBUTES) { gitAttributesMethod = "create"; @@ -114,7 +115,7 @@ static class PreserveLineEndingPolicy extends NoLambda.EqualityBasedOnSerializat @Override public String getEndingFor(File file) { // assume US-ASCII encoding (only line ending characters need to be decoded anyways) - try (Reader reader = new FileReader(file, StandardCharsets.US_ASCII)) { + try (Reader reader = new FileReader(file, US_ASCII)) { return getEndingFor(reader); } catch (IOException e) { throw new IllegalArgumentException("Could not determine line ending of file: " + file, e); @@ -186,7 +187,7 @@ public interface Policy extends Serializable, NoLambda { /** Returns true iff this file has unix line endings. */ public default boolean isUnix(File file) { - Objects.requireNonNull(file); + requireNonNull(file); String ending = getEndingFor(file); return ending.equals(UNIX.str()); } diff --git a/lib/src/main/java/com/diffplug/spotless/LintSuppression.java b/lib/src/main/java/com/diffplug/spotless/LintSuppression.java index 852d6eeb98..b897409fa1 100644 --- a/lib/src/main/java/com/diffplug/spotless/LintSuppression.java +++ b/lib/src/main/java/com/diffplug/spotless/LintSuppression.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.Serial; import java.io.Serializable; @@ -39,7 +41,7 @@ public void setPath(String path) { if (path.indexOf('\\') != -1) { throw new IllegalArgumentException("Path must use only unix style path separator `/`, this was " + path); } - this.path = Objects.requireNonNull(path); + this.path = requireNonNull(path); } public String getStep() { @@ -47,7 +49,7 @@ public String getStep() { } public void setStep(String step) { - this.step = Objects.requireNonNull(step); + this.step = requireNonNull(step); } public String getShortCode() { @@ -55,7 +57,7 @@ public String getShortCode() { } public void setShortCode(String shortCode) { - this.shortCode = Objects.requireNonNull(shortCode); + this.shortCode = requireNonNull(shortCode); } public boolean suppresses(String relativePath, FormatterStep formatterStep, Lint lint) { diff --git a/lib/src/main/java/com/diffplug/spotless/MoreIterables.java b/lib/src/main/java/com/diffplug/spotless/MoreIterables.java index 3a03127184..b3ce5db78b 100644 --- a/lib/src/main/java/com/diffplug/spotless/MoreIterables.java +++ b/lib/src/main/java/com/diffplug/spotless/MoreIterables.java @@ -16,6 +16,7 @@ package com.diffplug.spotless; import static com.diffplug.spotless.LibPreconditions.requireElementsNonNull; +import static java.util.Comparator.naturalOrder; import java.util.ArrayList; import java.util.Collection; @@ -40,7 +41,7 @@ static List toNullHostileList(Iterable input) { /** Sorts "raw" using {@link Comparator#naturalOrder()} and removes duplicates, throwing on null elements. */ static > List toSortedSet(Iterable raw) { - return toSortedSet(raw, Comparator.naturalOrder()); + return toSortedSet(raw, naturalOrder()); } /** Sorts "raw" and removes duplicates, throwing on null elements. */ diff --git a/lib/src/main/java/com/diffplug/spotless/PaddedCell.java b/lib/src/main/java/com/diffplug/spotless/PaddedCell.java index 18fb44acbb..04ea7ca412 100644 --- a/lib/src/main/java/com/diffplug/spotless/PaddedCell.java +++ b/lib/src/main/java/com/diffplug/spotless/PaddedCell.java @@ -16,15 +16,16 @@ package com.diffplug.spotless; import static com.diffplug.spotless.LibPreconditions.requireElementsNonNull; +import static java.util.Collections.unmodifiableList; +import static java.util.Comparator.comparing; +import static java.util.Objects.requireNonNull; +import static java.util.function.Function.identity; import java.io.File; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; import java.util.List; -import java.util.Objects; -import java.util.function.Function; /** * Models the result of applying a {@link Formatter} on a given {@link File} @@ -48,8 +49,8 @@ PaddedCell create(File file, List steps) { private final List steps; private PaddedCell(File file, Type type, List steps) { - this.file = Objects.requireNonNull(file, "file"); - this.type = Objects.requireNonNull(type, "type"); + this.file = requireNonNull(file, "file"); + this.type = requireNonNull(type, "type"); // defensive copy this.steps = new ArrayList<>(steps); requireElementsNonNull(this.steps); @@ -67,7 +68,7 @@ public Type type() { /** Returns the steps it takes to get to the result. */ public List steps() { - return Collections.unmodifiableList(steps); + return unmodifiableList(steps); } /** @@ -81,8 +82,8 @@ public List steps() { * */ public static PaddedCell check(Formatter formatter, File file) { - Objects.requireNonNull(formatter, "formatter"); - Objects.requireNonNull(file, "file"); + requireNonNull(formatter, "formatter"); + requireNonNull(file, "file"); byte[] rawBytes = ThrowingEx.get(() -> Files.readAllBytes(file.toPath())); String raw = new String(rawBytes, formatter.getEncoding()); String original = LineEnding.toUnix(raw); @@ -153,7 +154,7 @@ public String canonical() { // @formatter:off switch (type) { case CONVERGE: return steps.get(steps.size() - 1); - case CYCLE: return Collections.min(steps, Comparator.comparing(String::length).thenComparing(Function.identity())); + case CYCLE: return Collections.min(steps, comparing(String::length).thenComparing(identity())); case DIVERGE: throw new IllegalArgumentException("No canonical form for a diverging result"); default: throw new IllegalArgumentException("Unknown type: " + type); } diff --git a/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java b/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java index 05f5880129..f758707272 100644 --- a/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java +++ b/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless; +import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; import java.io.ByteArrayOutputStream; @@ -23,7 +24,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -223,11 +223,11 @@ public byte[] stdErr() { } public String stdOutUtf8() { - return new String(stdOut, StandardCharsets.UTF_8); + return new String(stdOut, UTF_8); } public String stdErrUtf8() { - return new String(stdErr, StandardCharsets.UTF_8); + return new String(stdErr, UTF_8); } /** Returns true if the exit code was not zero. */ diff --git a/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java b/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java index 86b7ecc370..24b3f4401c 100644 --- a/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java +++ b/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java @@ -115,8 +115,8 @@ public synchronized byte[] toByteArray() { return result; } - @SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "We want to use the default encoding here since this is contract on ByteArrayOutputStream") @Override + @SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "We want to use the default encoding here since this is contract on ByteArrayOutputStream") public synchronized String toString() { if (!isOverLimit) { return super.toString(); diff --git a/lib/src/main/java/com/diffplug/spotless/SerializableFileFilterImpl.java b/lib/src/main/java/com/diffplug/spotless/SerializableFileFilterImpl.java index f3a8f1f18d..2e4cddce9b 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-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,11 @@ package com.diffplug.spotless; import static com.diffplug.spotless.MoreIterables.toSortedSet; +import static java.util.Objects.requireNonNull; import java.io.File; import java.util.Arrays; import java.util.List; -import java.util.Objects; class SerializableFileFilterImpl { static class SkipFilesNamed extends NoLambda.EqualityBasedOnSerialization implements SerializableFileFilter { @@ -29,7 +29,7 @@ static class SkipFilesNamed extends NoLambda.EqualityBasedOnSerialization implem private final String[] namesToSkip; SkipFilesNamed(String... namesToSkip) { - Objects.requireNonNull(namesToSkip); + requireNonNull(namesToSkip); List sorted = toSortedSet(Arrays.asList(namesToSkip)); this.namesToSkip = sorted.toArray(new String[sorted.size()]); } diff --git a/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java b/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java index 82cdd5d3c2..1eccd9fc02 100644 --- a/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java +++ b/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless; +import static java.util.Objects.requireNonNull; + import java.io.IOException; import java.io.Serializable; import java.net.URLClassLoader; @@ -23,7 +25,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import javax.annotation.Nullable; @@ -43,7 +44,7 @@ static final class SerializedKey { final int hashCode; SerializedKey(Serializable key) { - Objects.requireNonNull(key); + requireNonNull(key); serialized = LazyForwardingEquality.toBytes(key); hashCode = Arrays.hashCode(serialized); } diff --git a/lib/src/main/java/com/diffplug/spotless/ValuePerStep.java b/lib/src/main/java/com/diffplug/spotless/ValuePerStep.java index 094edbb765..bfdefcef75 100644 --- a/lib/src/main/java/com/diffplug/spotless/ValuePerStep.java +++ b/lib/src/main/java/com/diffplug/spotless/ValuePerStep.java @@ -33,8 +33,7 @@ class ValuePerStep extends AbstractList { this.size = formatter.getSteps().size(); } - @Override - public @Nullable T set(int index, T newValue) { + @Nullable public @Override T set(int index, T newValue) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } diff --git a/lib/src/main/java/com/diffplug/spotless/annotations/Internal.java b/lib/src/main/java/com/diffplug/spotless/annotations/Internal.java index d87265fe2d..547c85795c 100644 --- a/lib/src/main/java/com/diffplug/spotless/annotations/Internal.java +++ b/lib/src/main/java/com/diffplug/spotless/annotations/Internal.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,6 +28,7 @@ * The user of the API should be warned that it may unexpectedly disappear in future versions of * Spotless. Usually the best place to put this warning is in the API's class JavaDoc. */ +@Documented @Retention(RetentionPolicy.CLASS) @Target({ ElementType.ANNOTATION_TYPE, @@ -36,7 +37,6 @@ ElementType.METHOD, ElementType.TYPE }) -@Documented public @interface Internal { } diff --git a/lib/src/main/java/com/diffplug/spotless/annotations/ReturnValuesAreNonnullByDefault.java b/lib/src/main/java/com/diffplug/spotless/annotations/ReturnValuesAreNonnullByDefault.java index ba96666131..74680f1fd8 100644 --- a/lib/src/main/java/com/diffplug/spotless/annotations/ReturnValuesAreNonnullByDefault.java +++ b/lib/src/main/java/com/diffplug/spotless/annotations/ReturnValuesAreNonnullByDefault.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ @Documented @Nonnull -@TypeQualifierDefault(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) +@TypeQualifierDefault(ElementType.METHOD) public @interface ReturnValuesAreNonnullByDefault {} diff --git a/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java b/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java index 8a9c6923c0..2662d21ca1 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless.biome; +import static java.nio.charset.StandardCharsets.ISO_8859_1; + import java.io.IOException; import java.math.BigInteger; import java.net.URI; @@ -23,7 +25,6 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse.BodyHandlers; import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; @@ -201,7 +202,7 @@ private boolean checkFileWithChecksum(Path filePath) { } try { var actualChecksum = computeChecksum(filePath, CHECKSUM_ALGORITHM); - var expectedChecksum = readTextFile(checksumPath, StandardCharsets.ISO_8859_1); + var expectedChecksum = readTextFile(checksumPath, ISO_8859_1); logger.debug("Expected checksum: {}, actual checksum: {}", expectedChecksum, actualChecksum); return Objects.equals(expectedChecksum, actualChecksum); } catch (final IOException ignored) { @@ -261,7 +262,7 @@ private Path getChecksumPath(Path file) { var parent = file.getParent(); var base = parent != null ? parent : file; var fileName = file.getFileName(); - var checksumName = fileName != null ? fileName.toString() + ".sha256" : "checksum.sha256"; + var checksumName = fileName != null ? fileName + ".sha256" : "checksum.sha256"; return base.resolve(checksumName); } @@ -363,7 +364,7 @@ private String readTextFile(Path file, Charset charset) throws IOException { private void writeChecksumFile(Path file, Path checksumPath) throws IOException { var checksum = computeChecksum(file, CHECKSUM_ALGORITHM); try (var out = Files.newOutputStream(checksumPath, WRITE_OPTIONS)) { - out.write(checksum.getBytes(StandardCharsets.ISO_8859_1)); + out.write(checksum.getBytes(ISO_8859_1)); } } } diff --git a/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java b/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java index 66b69112d5..b91e7204e1 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java @@ -15,11 +15,12 @@ */ package com.diffplug.spotless.biome; +import static java.nio.charset.StandardCharsets.UTF_8; + import java.io.File; import java.io.IOException; import java.io.Serializable; import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; @@ -419,7 +420,7 @@ private String[] buildBiomeCommand(File file) { * for Biome to finish formatting. */ private String format(ProcessRunner runner, String input, File file) throws IOException, InterruptedException { - var stdin = input.getBytes(StandardCharsets.UTF_8); + var stdin = input.getBytes(UTF_8); var args = buildBiomeCommand(file); if (logger.isDebugEnabled()) { logger.debug("Running Biome command to format code: '{}'", String.join(", ", args)); @@ -429,7 +430,7 @@ private String format(ProcessRunner runner, String input, File file) throws IOEx if (!stdErr.isEmpty()) { logger.warn("Biome stderr ouptut for file '{}'\n{}", file, stdErr.trim()); } - var formatted = runnerResult.assertExitZero(StandardCharsets.UTF_8); + var formatted = runnerResult.assertExitZero(UTF_8); // When biome encounters an ignored file, it does not output any formatted code // Ignored files come from (a) the biome.json configuration file and (b) from // a list of hard-coded file names, such as package.json or tsconfig.json. 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 7960670370..006be3a74f 100644 --- a/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java @@ -15,13 +15,14 @@ */ package com.diffplug.spotless.cpp; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.IOException; import java.io.Serializable; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import javax.annotation.Nullable; @@ -116,7 +117,7 @@ static class EqualityState implements Serializable { EqualityState(String version, @Nullable String style, ForeignExe pathToExe) { this.version = version; this.style = style; - this.exe = Objects.requireNonNull(pathToExe); + this.exe = requireNonNull(pathToExe); } String format(ProcessRunner runner, String input, File file) throws IOException, InterruptedException { @@ -130,7 +131,7 @@ String format(ProcessRunner runner, String input, File file) throws IOException, } final String[] 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); + return runner.exec(input.getBytes(UTF_8), processArgs).assertExitZero(UTF_8); } FormatterFunc.Closeable toFunc() { diff --git a/lib/src/main/java/com/diffplug/spotless/cpp/CppDefaults.java b/lib/src/main/java/com/diffplug/spotless/cpp/CppDefaults.java index 9a577f11fb..332dc3691c 100644 --- a/lib/src/main/java/com/diffplug/spotless/cpp/CppDefaults.java +++ b/lib/src/main/java/com/diffplug/spotless/cpp/CppDefaults.java @@ -15,8 +15,9 @@ */ package com.diffplug.spotless.cpp; +import static java.util.stream.Collectors.joining; + import java.util.Arrays; -import java.util.stream.Collectors; /** Common utilities for C/C++ */ public final class CppDefaults { @@ -37,6 +38,6 @@ private CppDefaults() {} "int8_t", "int16_t", "int32_t", "int64_t", "__int8_t", "__int16_t", "__int32_t", "__int64_t", "uint8_t", "uint16_t", "uint32_t", "uint64_t") - .stream().map(s -> "(? "(?(builder.ideaProperties); @@ -215,7 +216,7 @@ private String format(IdeaStepFormatterCleanupResources ideaStepFormatterCleanup // since we cannot directly work with the file, we need to write the unix string to a temporary file File tempFile = Files.createTempFile("spotless", file.getName()).toFile(); try { - Files.write(tempFile.toPath(), unix.getBytes(StandardCharsets.UTF_8)); + Files.write(tempFile.toPath(), unix.getBytes(UTF_8)); List params = getParams(tempFile); Map env = createEnv(); @@ -223,7 +224,7 @@ private String format(IdeaStepFormatterCleanupResources ideaStepFormatterCleanup var result = ideaStepFormatterCleanupResources.runner.exec(null, env, null, params); LOGGER.debug("command finished with exit code: {}", result.exitCode()); LOGGER.debug("command finished with stdout: {}", - result.assertExitZero(StandardCharsets.UTF_8)); + result.assertExitZero(UTF_8)); return Files.readString(tempFile.toPath()); } finally { Files.delete(tempFile.toPath()); @@ -280,7 +281,7 @@ private List getParams(File file) { } builder.add("-charset").add("UTF-8"); builder.add(ThrowingEx.get(file::getCanonicalPath)); - return builder.build().collect(Collectors.toList()); + return builder.build().collect(toList()); } private FormatterFunc.Closeable toFunc() { 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 7636f3606d..369640f4ac 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java @@ -15,10 +15,11 @@ */ package com.diffplug.spotless.generic; +import static java.util.Objects.requireNonNull; +import static java.util.stream.Collectors.joining; + import java.io.Serial; import java.io.Serializable; -import java.util.Objects; -import java.util.stream.Collectors; import javax.annotation.Nullable; import javax.script.ScriptEngine; @@ -43,9 +44,9 @@ private Jsr223Step(@Nullable JarState.Promised jarState, String engine, String s } public static FormatterStep create(String name, @Nullable String dependency, CharSequence engine, CharSequence script, Provisioner provisioner) { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(engine, "engine"); - Objects.requireNonNull(script, "script"); + requireNonNull(name, "name"); + requireNonNull(engine, "engine"); + requireNonNull(script, "script"); return FormatterStep.create(name, new Jsr223Step(dependency == null ? null : JarState.promise(() -> JarState.from(dependency, provisioner)), engine.toString(), script.toString()), Jsr223Step::equalityState, @@ -81,7 +82,7 @@ FormatterFunc toFormatter() { if (scriptEngine == null) { throw new IllegalArgumentException("Unknown script engine '" + engine + "'. Available engines: " - + scriptEngineManager.getEngineFactories().stream().flatMap(f -> f.getNames().stream()).collect(Collectors.joining(", "))); + + scriptEngineManager.getEngineFactories().stream().flatMap(f -> f.getNames().stream()).collect(joining(", "))); } // evaluate script code 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 51350473a6..a7d0899b98 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java @@ -15,6 +15,10 @@ */ package com.diffplug.spotless.generic; +import static java.util.Objects.requireNonNull; +import static java.util.regex.Pattern.MULTILINE; +import static java.util.regex.Pattern.UNIX_LINES; + import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -73,10 +77,10 @@ public static LicenseHeaderStep headerDelimiter(ThrowingEx.Supplier head private LicenseHeaderStep(@Nullable String name, @Nullable String contentPattern, ThrowingEx.Supplier headerLazy, String delimiter, String yearSeparator, Supplier yearMode, @Nullable String skipLinesMatching) { this.name = sanitizeName(name); this.contentPattern = sanitizePattern(contentPattern); - this.headerLazy = Objects.requireNonNull(headerLazy); - this.delimiter = Objects.requireNonNull(delimiter); - this.yearSeparator = Objects.requireNonNull(yearSeparator); - this.yearMode = Objects.requireNonNull(yearMode); + this.headerLazy = requireNonNull(headerLazy); + this.delimiter = requireNonNull(delimiter); + this.yearSeparator = requireNonNull(yearSeparator); + this.yearMode = requireNonNull(yearMode); this.skipLinesMatching = sanitizePattern(skipLinesMatching); } @@ -234,7 +238,7 @@ private Runtime(String licenseHeader, String delimiter, String yearSeparator, bo if (!licenseHeader.isEmpty() && !licenseHeader.endsWith("\n")) { licenseHeader = licenseHeader + "\n"; } - this.delimiterPattern = Pattern.compile('^' + delimiter, Pattern.UNIX_LINES | Pattern.MULTILINE); + this.delimiterPattern = Pattern.compile('^' + delimiter, UNIX_LINES | MULTILINE); this.skipLinesMatching = skipLinesMatching == null ? null : Pattern.compile(skipLinesMatching); this.hasFileToken = FILENAME_PATTERN.matcher(licenseHeader).find(); diff --git a/lib/src/main/java/com/diffplug/spotless/generic/NativeCmdStep.java b/lib/src/main/java/com/diffplug/spotless/generic/NativeCmdStep.java index d655fbefa5..c41fdce0d2 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/NativeCmdStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/NativeCmdStep.java @@ -15,13 +15,14 @@ */ package com.diffplug.spotless.generic; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.IOException; import java.io.Serializable; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import com.diffplug.spotless.FileSignature; import com.diffplug.spotless.FormatterFunc; @@ -33,8 +34,8 @@ public final class NativeCmdStep { private NativeCmdStep() {} public static FormatterStep create(String name, File pathToExe, List arguments) { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(pathToExe, "pathToExe"); + requireNonNull(name, "name"); + requireNonNull(pathToExe, "pathToExe"); return FormatterStep.createLazy(name, () -> new State(FileSignature.promise(pathToExe), arguments), State::toRuntime, Runtime::toFunc); } @@ -69,7 +70,7 @@ String format(ProcessRunner runner, String input) throws IOException, Interrupte if (arguments != null) { argumentsWithPathToExe.addAll(arguments); } - return runner.exec(input.getBytes(StandardCharsets.UTF_8), argumentsWithPathToExe).assertExitZero(StandardCharsets.UTF_8); + return runner.exec(input.getBytes(UTF_8), argumentsWithPathToExe).assertExitZero(UTF_8); } FormatterFunc.Closeable toFunc() { diff --git a/lib/src/main/java/com/diffplug/spotless/generic/ReplaceRegexStep.java b/lib/src/main/java/com/diffplug/spotless/generic/ReplaceRegexStep.java index 33a4e4c12e..1aba0a5e4e 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/ReplaceRegexStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/ReplaceRegexStep.java @@ -15,11 +15,14 @@ */ package com.diffplug.spotless.generic; +import static java.util.Objects.requireNonNull; +import static java.util.regex.Pattern.MULTILINE; +import static java.util.regex.Pattern.UNIX_LINES; + import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.regex.Pattern; import com.diffplug.spotless.FormatterFunc; @@ -31,20 +34,20 @@ public final class ReplaceRegexStep { private ReplaceRegexStep() {} public static FormatterStep create(String name, String regex, String replacement) { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(regex, "regex"); - Objects.requireNonNull(replacement, "replacement"); + requireNonNull(name, "name"); + requireNonNull(regex, "regex"); + requireNonNull(replacement, "replacement"); return FormatterStep.createLazy(name, - () -> new State(Pattern.compile(regex, Pattern.UNIX_LINES | Pattern.MULTILINE), replacement), + () -> new State(Pattern.compile(regex, UNIX_LINES | MULTILINE), replacement), State::toFormatter); } public static FormatterStep lint(String name, String regex, String lintDetail) { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(regex, "regex"); - Objects.requireNonNull(lintDetail, "lintDetail"); + requireNonNull(name, "name"); + requireNonNull(regex, "regex"); + requireNonNull(lintDetail, "lintDetail"); return FormatterStep.createLazy(name, - () -> new LintState(Pattern.compile(regex, Pattern.UNIX_LINES | Pattern.MULTILINE), name, lintDetail), + () -> new LintState(Pattern.compile(regex, UNIX_LINES | MULTILINE), name, lintDetail), LintState::toLinter); } diff --git a/lib/src/main/java/com/diffplug/spotless/generic/ReplaceStep.java b/lib/src/main/java/com/diffplug/spotless/generic/ReplaceStep.java index aaf0dccd51..bfa8d2b3b0 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/ReplaceStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/ReplaceStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,9 @@ */ package com.diffplug.spotless.generic; +import static java.util.Objects.requireNonNull; + import java.io.Serializable; -import java.util.Objects; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.FormatterStep; @@ -26,9 +27,9 @@ public final class ReplaceStep { private ReplaceStep() {} public static FormatterStep create(String name, CharSequence target, CharSequence replacement) { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(target, "target"); - Objects.requireNonNull(replacement, "replacement"); + requireNonNull(name, "name"); + requireNonNull(target, "target"); + requireNonNull(replacement, "replacement"); return FormatterStep.createLazy(name, () -> new State(target, replacement), State::toFormatter); diff --git a/lib/src/main/java/com/diffplug/spotless/generic/TestEnvVars.java b/lib/src/main/java/com/diffplug/spotless/generic/TestEnvVars.java index 44278555aa..72f9564e38 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/TestEnvVars.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/TestEnvVars.java @@ -15,12 +15,13 @@ */ package com.diffplug.spotless.generic; +import static java.util.Objects.requireNonNull; + import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; -import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.stream.Stream; @@ -72,7 +73,7 @@ private static Stream candidateTestEnvLocations() { builder.add( Path.of(System.getProperty("user.dir"), "testenv.properties")); builder.add( - Objects.requireNonNull(Path.of(System.getProperty("user.dir")).getParent()).resolve("testenv.properties")); + requireNonNull(Path.of(System.getProperty("user.dir")).getParent()).resolve("testenv.properties")); return builder.build(); } diff --git a/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsStep.java b/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsStep.java index aa68d7e6c7..89fe0dcc07 100644 --- a/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsStep.java @@ -15,11 +15,12 @@ */ package com.diffplug.spotless.gherkin; +import static java.util.Objects.requireNonNull; + import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.util.Objects; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.FormatterStep; @@ -47,7 +48,7 @@ public static String defaultVersion() { public static FormatterStep create(GherkinUtilsConfig gherkinSimpleConfig, String formatterVersion, Provisioner provisioner) { - Objects.requireNonNull(provisioner, "provisioner cannot be null"); + requireNonNull(provisioner, "provisioner cannot be null"); return FormatterStep.create(NAME, new GherkinUtilsStep(JarState.promise(() -> JarState.from(MAVEN_COORDINATE + formatterVersion, provisioner)), gherkinSimpleConfig), GherkinUtilsStep::equalityState, diff --git a/lib/src/main/java/com/diffplug/spotless/go/GofmtFormatStep.java b/lib/src/main/java/com/diffplug/spotless/go/GofmtFormatStep.java index a4354e89d2..e159baea5d 100644 --- a/lib/src/main/java/com/diffplug/spotless/go/GofmtFormatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/go/GofmtFormatStep.java @@ -15,14 +15,15 @@ */ package com.diffplug.spotless.go; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.IOException; import java.io.Serializable; -import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import javax.annotation.Nullable; @@ -104,7 +105,7 @@ static class EqualityState implements Serializable { public EqualityState(String version, ForeignExe goExecutable) { this.version = version; - this.exe = Objects.requireNonNull(goExecutable); + this.exe = requireNonNull(goExecutable); } String format(ProcessRunner runner, String input, File file) throws IOException, InterruptedException { @@ -116,7 +117,7 @@ String format(ProcessRunner runner, String input, File file) throws IOException, } String pathToGoFmt = goBasePath.resolve("gofmt").toString(); processArgs.add(pathToGoFmt); - return runner.exec(input.getBytes(StandardCharsets.UTF_8), processArgs).assertExitZero(StandardCharsets.UTF_8); + return runner.exec(input.getBytes(UTF_8), processArgs).assertExitZero(UTF_8); } FormatterFunc.Closeable toFunc() { diff --git a/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java b/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java index ec18823d3a..a7cd29bfe2 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless.java; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.Serial; import java.io.Serializable; @@ -22,7 +24,6 @@ import java.lang.reflect.Method; import java.nio.file.Path; import java.util.List; -import java.util.Objects; import com.diffplug.spotless.Formatter; import com.diffplug.spotless.FormatterFunc; @@ -111,12 +112,12 @@ static FormatterStep createWithStepName(String stepName, List excluded, boolean includeDraft, Provisioner provisioner) { - Objects.requireNonNull(groupArtifact, "groupArtifact"); + requireNonNull(groupArtifact, "groupArtifact"); if (groupArtifact.chars().filter(ch -> ch == ':').count() != 1) { throw new IllegalArgumentException("groupArtifact must be in the form 'groupId:artifactId'. it was: " + groupArtifact); } - Objects.requireNonNull(version, "version"); - Objects.requireNonNull(provisioner, "provisioner"); + requireNonNull(version, "version"); + requireNonNull(provisioner, "provisioner"); return FormatterStep.create(stepName, new CleanthatJavaStep(JarState.promise(() -> JarState.from(groupArtifact + ":" + version, provisioner)), version, sourceJdkVersion, included, excluded, includeDraft), CleanthatJavaStep::equalityState, @@ -136,7 +137,7 @@ public static FormatterStep create(String groupArtifact, /** Get default formatter version */ public static String defaultVersion() { - return Objects.requireNonNull(JVM_SUPPORT.getRecommendedFormatterVersion()); + return requireNonNull(JVM_SUPPORT.getRecommendedFormatterVersion()); } public static String defaultGroupArtifact() { diff --git a/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java b/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java index bfdfc0ba09..0fe7240cc2 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java @@ -15,10 +15,11 @@ */ package com.diffplug.spotless.java; +import static java.util.Collections.emptyList; + import java.io.Serial; import java.io.Serializable; import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -417,7 +418,7 @@ public final class FormatAnnotationsStep implements Serializable { private static final String NAME = "No line break between type annotation and type"; public static FormatterStep create() { - return create(Collections.emptyList(), Collections.emptyList()); + return create(emptyList(), emptyList()); } public static FormatterStep create(List addedTypeAnnotations, List removedTypeAnnotations) { diff --git a/lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java b/lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java index 793da7f272..2675f6dc81 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java @@ -15,10 +15,11 @@ */ package com.diffplug.spotless.java; +import static java.util.Objects.requireNonNull; + import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; -import java.util.Objects; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.FormatterStep; @@ -97,13 +98,13 @@ static FormatterStep createRemoveUnusedImportsOnly(Provisioner provisioner) { } private static FormatterStep createInternally(String name, String groupArtifact, String version, String style, Provisioner provisioner, boolean reflowLongStrings, boolean reorderImports, boolean formatJavadoc, boolean removeImports) { - Objects.requireNonNull(groupArtifact, "groupArtifact"); + requireNonNull(groupArtifact, "groupArtifact"); if (groupArtifact.chars().filter(ch -> ch == ':').count() != 1) { throw new IllegalArgumentException("groupArtifact must be in the form 'groupId:artifactId'"); } - Objects.requireNonNull(version, "version"); - Objects.requireNonNull(style, "style"); - Objects.requireNonNull(provisioner, "provisioner"); + requireNonNull(version, "version"); + requireNonNull(style, "style"); + requireNonNull(provisioner, "provisioner"); GoogleJavaFormatStep step = new GoogleJavaFormatStep(JarState.promise(() -> JarState.from(groupArtifact + ":" + version, provisioner)), version, style, reflowLongStrings, reorderImports, formatJavadoc); if (removeImports) { @@ -131,7 +132,7 @@ public static String defaultGroupArtifact() { /** Get default formatter version */ public static String defaultVersion() { - return Objects.requireNonNull(JVM_SUPPORT.getRecommendedFormatterVersion()); + return requireNonNull(JVM_SUPPORT.getRecommendedFormatterVersion()); } public static String defaultStyle() { 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 62596ef42c..ec4171f4e6 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/ImportOrderStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/ImportOrderStep.java @@ -16,6 +16,9 @@ package com.diffplug.spotless.java; import static com.diffplug.spotless.java.LibJavaPreconditions.requireElementsNonNull; +import static java.util.Map.Entry.comparingByKey; +import static java.util.Objects.requireNonNull; +import static java.util.stream.Collectors.toCollection; import java.io.File; import java.io.IOException; @@ -28,11 +31,9 @@ import java.util.Arrays; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Set; import java.util.TreeSet; import java.util.function.Supplier; -import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; @@ -82,7 +83,7 @@ public FormatterStep createFrom(File importsFile) { public FormatterStep createFrom(boolean wildcardsLast, boolean semanticSort, Set treatAsPackage, Set treatAsClass, File importsFile) { - Objects.requireNonNull(importsFile); + requireNonNull(importsFile); return createFrom(wildcardsLast, semanticSort, treatAsPackage, treatAsClass, () -> getImportOrder(importsFile)); } @@ -99,9 +100,9 @@ private static List getImportOrder(File importsFile) { return lines.filter(line -> !line.startsWith("#")) // parse 0=input .map(ImportOrderStep::splitIntoIndexAndName) - .sorted(Map.Entry.comparingByKey()) + .sorted(comparingByKey()) .map(Map.Entry::getValue) - .collect(Collectors.toCollection(ArrayList::new)); + .collect(toCollection(ArrayList::new)); } catch (IOException e) { throw new UncheckedIOException(e); } 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 e9e28c2576..305d814b7b 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java +++ b/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless.java; +import static java.util.stream.Collectors.toList; + import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; @@ -25,7 +27,6 @@ import java.util.Map; import java.util.Objects; import java.util.Set; -import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; @@ -57,7 +58,7 @@ public ImportsGroup(String importOrder, Set knownGroupings) { this.subGroups = Stream.of(importOrder.split("\\" + SUBGROUP_SEPARATOR, -1)) .map(this::normalizeStatic) .filter(group -> !knownGroupings.contains(group)) - .collect(Collectors.toList()); + .collect(toList()); knownGroupings.addAll(this.subGroups); } @@ -91,7 +92,7 @@ private List sort(List imports, String lineFormat) { private ImportSorterImpl(List importOrder, boolean wildcardsLast, boolean semanticSort, Set treatAsPackage, Set treatAsClass) { - importsGroups = importOrder.stream().filter(Objects::nonNull).map(order -> new ImportsGroup(order, knownGroupings)).collect(Collectors.toList()); + importsGroups = importOrder.stream().filter(Objects::nonNull).map(order -> new ImportsGroup(order, knownGroupings)).collect(toList()); putStaticItemIfNotExists(importsGroups); putCatchAllGroupIfNotExists(importsGroups); @@ -101,7 +102,7 @@ private ImportSorterImpl(List importOrder, boolean wildcardsLast, boolea ordering = new LexicographicalOrderingComparator(wildcardsLast); } - List subgroups = importsGroups.stream().map(ImportsGroup::getSubGroups).flatMap(Collection::stream).collect(Collectors.toList()); + List subgroups = importsGroups.stream().map(ImportsGroup::getSubGroups).flatMap(Collection::stream).collect(toList()); this.allImportOrderItems.addAll(subgroups); } diff --git a/lib/src/main/java/com/diffplug/spotless/java/LibJavaPreconditions.java b/lib/src/main/java/com/diffplug/spotless/java/LibJavaPreconditions.java index eabab90b9d..14dedec0ff 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/LibJavaPreconditions.java +++ b/lib/src/main/java/com/diffplug/spotless/java/LibJavaPreconditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,16 +15,16 @@ */ package com.diffplug.spotless.java; -import java.util.Objects; +import static java.util.Objects.requireNonNull; final class LibJavaPreconditions { // prevent direct instantiation private LibJavaPreconditions() {} static > I requireElementsNonNull(I elements) { - Objects.requireNonNull(elements); + requireNonNull(elements); for (Object element : elements) { - Objects.requireNonNull(element); + requireNonNull(element); } return elements; } diff --git a/lib/src/main/java/com/diffplug/spotless/java/PalantirJavaFormatStep.java b/lib/src/main/java/com/diffplug/spotless/java/PalantirJavaFormatStep.java index b717787d86..7a6ff78eee 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/PalantirJavaFormatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/PalantirJavaFormatStep.java @@ -15,10 +15,11 @@ */ package com.diffplug.spotless.java; +import static java.util.Objects.requireNonNull; + import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; -import java.util.Objects; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.FormatterStep; @@ -78,9 +79,9 @@ public static FormatterStep create(String version, String style, Provisioner pro * format style. */ public static FormatterStep create(String version, String style, boolean formatJavadoc, Provisioner provisioner) { - Objects.requireNonNull(version, "version"); - Objects.requireNonNull(style, "style"); - Objects.requireNonNull(provisioner, "provisioner"); + requireNonNull(version, "version"); + requireNonNull(style, "style"); + requireNonNull(provisioner, "provisioner"); return FormatterStep.create(NAME, new PalantirJavaFormatStep(JarState.promise(() -> JarState.from(MAVEN_COORDINATE + version, provisioner)), version, style, formatJavadoc), diff --git a/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java b/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java index 590432aedc..cda698bba0 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java @@ -15,10 +15,11 @@ */ package com.diffplug.spotless.java; +import static java.util.Objects.requireNonNull; + import java.io.Serial; import java.io.Serializable; import java.util.List; -import java.util.Objects; import com.diffplug.spotless.FormatterStep; import com.diffplug.spotless.Provisioner; @@ -48,7 +49,7 @@ public static FormatterStep create(Provisioner provisioner) { } public static FormatterStep create(String unusedImportRemover, Provisioner provisioner) { - Objects.requireNonNull(provisioner, "provisioner"); + requireNonNull(provisioner, "provisioner"); switch (unusedImportRemover) { case GJF: return GoogleJavaFormatStep.createRemoveUnusedImportsOnly(provisioner); diff --git a/lib/src/main/java/com/diffplug/spotless/json/JacksonConfig.java b/lib/src/main/java/com/diffplug/spotless/json/JacksonConfig.java index 2363c15069..4092f98cb8 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/JacksonConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/json/JacksonConfig.java @@ -15,9 +15,10 @@ */ package com.diffplug.spotless.json; +import static java.util.Collections.unmodifiableMap; + import java.io.Serial; import java.io.Serializable; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; @@ -42,7 +43,7 @@ public class JacksonConfig implements Serializable { protected Map featureToToggle = new TreeMap<>(DEFAULT_FEATURE_TOGGLES); public Map getFeatureToToggle() { - return Collections.unmodifiableMap(featureToToggle); + return unmodifiableMap(featureToToggle); } public void setFeatureToToggle(Map featureToToggle) { diff --git a/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonConfig.java b/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonConfig.java index 9c9578c97e..7306e92115 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonConfig.java @@ -15,8 +15,9 @@ */ package com.diffplug.spotless.json; +import static java.util.Collections.unmodifiableMap; + import java.io.Serial; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; @@ -34,7 +35,7 @@ public class JacksonJsonConfig extends JacksonConfig { protected boolean spaceBeforeSeparator; public Map getJsonFeatureToToggle() { - return Collections.unmodifiableMap(jsonFeatureToToggle); + return unmodifiableMap(jsonFeatureToToggle); } /** diff --git a/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonStep.java b/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonStep.java index ec2a9726c3..1eea6fae77 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonStep.java +++ b/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonStep.java @@ -15,11 +15,12 @@ */ package com.diffplug.spotless.json; +import static java.util.Objects.requireNonNull; + import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.util.Objects; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.FormatterStep; @@ -56,7 +57,7 @@ public static FormatterStep create(Provisioner provisioner) { public static FormatterStep create(JacksonJsonConfig jacksonConfig, String jacksonVersion, Provisioner provisioner) { - Objects.requireNonNull(provisioner, "provisioner cannot be null"); + requireNonNull(provisioner, "provisioner cannot be null"); return FormatterStep.create(NAME, new JacksonJsonStep(JarState.promise(() -> JarState.from(MAVEN_COORDINATE + jacksonVersion, provisioner)), jacksonConfig), JacksonJsonStep::equalityState, diff --git a/lib/src/main/java/com/diffplug/spotless/json/JsonPatchStep.java b/lib/src/main/java/com/diffplug/spotless/json/JsonPatchStep.java index dce0c3a307..a683450524 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/JsonPatchStep.java +++ b/lib/src/main/java/com/diffplug/spotless/json/JsonPatchStep.java @@ -15,13 +15,14 @@ */ package com.diffplug.spotless.json; +import static java.util.Objects.requireNonNull; + import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; -import java.util.Objects; import javax.annotation.Nullable; @@ -54,9 +55,9 @@ public static FormatterStep create(String patchString, Provisioner provisioner) } public static FormatterStep create(String zjsonPatchVersion, String patchString, Provisioner provisioner) { - Objects.requireNonNull(zjsonPatchVersion, "zjsonPatchVersion cannot be null"); - Objects.requireNonNull(patchString, "patchString cannot be null"); - Objects.requireNonNull(provisioner, "provisioner cannot be null"); + requireNonNull(zjsonPatchVersion, "zjsonPatchVersion cannot be null"); + requireNonNull(patchString, "patchString cannot be null"); + requireNonNull(provisioner, "provisioner cannot be null"); return FormatterStep.create(NAME, new JsonPatchStep(JarState.promise(() -> JarState.from(MAVEN_COORDINATE + ":" + zjsonPatchVersion, provisioner)), patchString, null), JsonPatchStep::equalityState, @@ -68,9 +69,9 @@ public static FormatterStep create(List> patch, Provisioner } public static FormatterStep create(String zjsonPatchVersion, List> patch, Provisioner provisioner) { - Objects.requireNonNull(zjsonPatchVersion, "zjsonPatchVersion cannot be null"); - Objects.requireNonNull(patch, "patch cannot be null"); - Objects.requireNonNull(provisioner, "provisioner cannot be null"); + requireNonNull(zjsonPatchVersion, "zjsonPatchVersion cannot be null"); + requireNonNull(patch, "patch cannot be null"); + requireNonNull(provisioner, "provisioner cannot be null"); return FormatterStep.create(NAME, new JsonPatchStep(JarState.promise(() -> JarState.from(MAVEN_COORDINATE + ":" + zjsonPatchVersion, provisioner)), null, patch), JsonPatchStep::equalityState, diff --git a/lib/src/main/java/com/diffplug/spotless/json/JsonSimpleStep.java b/lib/src/main/java/com/diffplug/spotless/json/JsonSimpleStep.java index 3fbe8ae7b9..e810aa66d0 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/JsonSimpleStep.java +++ b/lib/src/main/java/com/diffplug/spotless/json/JsonSimpleStep.java @@ -15,12 +15,13 @@ */ package com.diffplug.spotless.json; +import static java.util.Objects.requireNonNull; + import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.Objects; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.FormatterStep; @@ -46,7 +47,7 @@ private JsonSimpleStep(JarState.Promised jarState, int indentSpaces) { } public static FormatterStep create(int indent, Provisioner provisioner) { - Objects.requireNonNull(provisioner, "provisioner cannot be null"); + requireNonNull(provisioner, "provisioner cannot be null"); return FormatterStep.create(NAME, new JsonSimpleStep(JarState.promise(() -> JarState.from(MAVEN_COORDINATE + DEFAULT_VERSION, provisioner)), indent), JsonSimpleStep::equalityState, diff --git a/lib/src/main/java/com/diffplug/spotless/json/gson/GsonStep.java b/lib/src/main/java/com/diffplug/spotless/json/gson/GsonStep.java index 5ad4034bb6..c5a5c356b5 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/gson/GsonStep.java +++ b/lib/src/main/java/com/diffplug/spotless/json/gson/GsonStep.java @@ -15,11 +15,12 @@ */ package com.diffplug.spotless.json.gson; +import static java.util.Objects.requireNonNull; + import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.util.Objects; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.FormatterStep; @@ -43,7 +44,7 @@ private GsonStep(JarState.Promised jarState, GsonConfig gsonConfig) { } public static FormatterStep create(GsonConfig gsonConfig, Provisioner provisioner) { - Objects.requireNonNull(provisioner, "provisioner cannot be null"); + requireNonNull(provisioner, "provisioner cannot be null"); return FormatterStep.create(NAME, new GsonStep(JarState.promise(() -> JarState.from(MAVEN_COORDINATES + ":" + gsonConfig.getVersion(), provisioner)), gsonConfig), GsonStep::equalityState, diff --git a/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java b/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java index 8efe5a61b7..fda31ce139 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java @@ -15,11 +15,12 @@ */ package com.diffplug.spotless.kotlin; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; -import java.util.Objects; import javax.annotation.Nullable; @@ -74,8 +75,8 @@ public static FormatterStep create(String versionDiktat, Provisioner provisioner if (BadSemver.version(versionDiktat) < BadSemver.version(MIN_SUPPORTED_VERSION)) { throw new IllegalStateException("Minimum required Diktat version is " + MIN_SUPPORTED_VERSION + ", you tried " + versionDiktat + " which is too old"); } - Objects.requireNonNull(versionDiktat, "versionDiktat"); - Objects.requireNonNull(provisioner, "provisioner"); + requireNonNull(versionDiktat, "versionDiktat"); + requireNonNull(provisioner, "provisioner"); final String diktatCoordinate; if (BadSemver.version(versionDiktat) >= BadSemver.version(PACKAGE_RELOCATED_VERSION)) { diktatCoordinate = MAVEN_COORDINATE + versionDiktat; diff --git a/lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java b/lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java index c022af784d..4842157f33 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java @@ -15,14 +15,16 @@ */ package com.diffplug.spotless.kotlin; +import static java.util.Collections.emptyList; +import static java.util.Collections.emptyMap; +import static java.util.Objects.requireNonNull; + import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Set; import java.util.TreeMap; @@ -63,7 +65,7 @@ public static FormatterStep create(Provisioner provisioner) { } public static FormatterStep create(String version, Provisioner provisioner) { - return create(version, provisioner, null, Collections.emptyMap(), Collections.emptyList()); + return create(version, provisioner, null, emptyMap(), emptyList()); } public static FormatterStep create(String version, @@ -71,8 +73,8 @@ public static FormatterStep create(String version, @Nullable FileSignature editorConfig, Map editorConfigOverride, List customRuleSets) { - Objects.requireNonNull(version, "version"); - Objects.requireNonNull(provisioner, "provisioner"); + requireNonNull(version, "version"); + requireNonNull(provisioner, "provisioner"); String ktlintCoordinate = (version.startsWith("0.") ? MAVEN_COORDINATE_0_DOT : MAVEN_COORDINATE_1_DOT) + version; Set mavenCoordinates = new HashSet<>(customRuleSets); mavenCoordinates.add(ktlintCoordinate); 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 8dafc0c51f..5d31bba75b 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java @@ -19,13 +19,14 @@ import static com.diffplug.spotless.kotlin.KtfmtStep.Style.DROPBOX; import static com.diffplug.spotless.kotlin.KtfmtStep.Style.META; import static com.diffplug.spotless.kotlin.KtfmtStep.TrailingCommaManagementStrategy.ONLY_ADD; +import static java.util.Objects.requireNonNull; +import static java.util.Objects.requireNonNullElse; import java.io.Serial; 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; @@ -60,10 +61,10 @@ private KtfmtStep(String version, JarState.Promised jarState, @Nullable Style style, @Nullable KtfmtFormattingOptions options) { - this.version = Objects.requireNonNull(version, "version"); + this.version = requireNonNull(version, "version"); this.style = style; this.options = options; - this.jarState = Objects.requireNonNull(jarState, "jarState"); + this.jarState = requireNonNull(jarState, "jarState"); } /** @@ -210,8 +211,8 @@ public static FormatterStep create(String version, Provisioner provisioner) { * Creates a step which formats everything - code, import order, and unused imports. */ public static FormatterStep create(String version, Provisioner provisioner, @Nullable Style style, @Nullable KtfmtFormattingOptions options) { - Objects.requireNonNull(version, "version"); - Objects.requireNonNull(provisioner, "provisioner"); + requireNonNull(version, "version"); + requireNonNull(provisioner, "provisioner"); return FormatterStep.create(NAME, new KtfmtStep(version, JarState.promise(() -> JarState.from(MAVEN_COORDINATE + version, provisioner)), style, options), KtfmtStep::equalityState, @@ -389,45 +390,45 @@ private Object getCustomFormattingOptions(Class formatterClass) throws Except if (options != null) { if (BadSemver.version(version) < BadSemver.version(0, 17)) { formattingOptions = formattingOptions.getClass().getConstructor(int.class, int.class, int.class).newInstance( - /* maxWidth = */ Objects.requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), - /* blockIndent = */ Objects.requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), - /* continuationIndent = */ Objects.requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions))); + /* maxWidth = */ requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), + /* blockIndent = */ requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), + /* continuationIndent = */ requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions))); } else if (BadSemver.version(version) < BadSemver.version(0, 19)) { formattingOptions = formattingOptions.getClass().getConstructor(int.class, int.class, int.class, boolean.class, boolean.class).newInstance( - /* maxWidth = */ Objects.requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), - /* blockIndent = */ Objects.requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), - /* continuationIndent = */ Objects.requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), - /* removeUnusedImports = */ Objects.requireNonNullElse(options.removeUnusedImports, (Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), + /* maxWidth = */ requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), + /* blockIndent = */ requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), + /* continuationIndent = */ requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), + /* removeUnusedImports = */ requireNonNullElse(options.removeUnusedImports, (Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), /* debuggingPrintOpsAfterFormatting = */ (Boolean) formattingOptionsClass.getMethod("getDebuggingPrintOpsAfterFormatting").invoke(formattingOptions)); } else if (BadSemver.version(version) < BadSemver.version(0, 47)) { Class styleClass = classLoader.loadClass(formattingOptionsClass.getName() + "$Style"); formattingOptions = formattingOptions.getClass().getConstructor(styleClass, int.class, int.class, int.class, boolean.class, boolean.class).newInstance( /* style = */ formattingOptionsClass.getMethod("getStyle").invoke(formattingOptions), - /* maxWidth = */ Objects.requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), - /* blockIndent = */ Objects.requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), - /* continuationIndent = */ Objects.requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), - /* removeUnusedImports = */ Objects.requireNonNullElse(options.removeUnusedImports, (Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), + /* maxWidth = */ requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), + /* blockIndent = */ requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), + /* continuationIndent = */ requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), + /* removeUnusedImports = */ requireNonNullElse(options.removeUnusedImports, (Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), /* debuggingPrintOpsAfterFormatting = */ (Boolean) formattingOptionsClass.getMethod("getDebuggingPrintOpsAfterFormatting").invoke(formattingOptions)); } else if (BadSemver.version(version) < BadSemver.version(0, 57)) { Class styleClass = classLoader.loadClass(formattingOptionsClass.getName() + "$Style"); formattingOptions = formattingOptions.getClass().getConstructor(styleClass, int.class, int.class, int.class, boolean.class, boolean.class, boolean.class).newInstance( /* style = */ formattingOptionsClass.getMethod("getStyle").invoke(formattingOptions), - /* maxWidth = */ Objects.requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), - /* blockIndent = */ Objects.requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), - /* continuationIndent = */ Objects.requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), - /* removeUnusedImports = */ Objects.requireNonNullElse(options.removeUnusedImports, (Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), + /* maxWidth = */ requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), + /* blockIndent = */ requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), + /* continuationIndent = */ requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), + /* removeUnusedImports = */ requireNonNullElse(options.removeUnusedImports, (Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), /* debuggingPrintOpsAfterFormatting = */ (Boolean) formattingOptionsClass.getMethod("getDebuggingPrintOpsAfterFormatting").invoke(formattingOptions), - /* manageTrailingCommas = */ Objects.requireNonNullElse(getManageTrailingCommasFrom(options.trailingCommaManagementStrategy), (Boolean) formattingOptionsClass.getMethod("getManageTrailingCommas").invoke(formattingOptions))); + /* manageTrailingCommas = */ requireNonNullElse(getManageTrailingCommasFrom(options.trailingCommaManagementStrategy), (Boolean) formattingOptionsClass.getMethod("getManageTrailingCommas").invoke(formattingOptions))); } else { Class styleClass = classLoader.loadClass(formattingOptionsClass.getName() + "$Style"); formattingOptions = formattingOptions.getClass().getConstructor(styleClass, int.class, int.class, int.class, boolean.class, boolean.class, TrailingCommaManagementStrategy.class).newInstance( /* style = */ formattingOptionsClass.getMethod("getStyle").invoke(formattingOptions), - /* maxWidth = */ Objects.requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), - /* blockIndent = */ Objects.requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), - /* continuationIndent = */ Objects.requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), - /* removeUnusedImports = */ Objects.requireNonNullElse(options.removeUnusedImports, (Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), + /* maxWidth = */ requireNonNullElse(options.maxWidth, (Integer) formattingOptionsClass.getMethod("getMaxWidth").invoke(formattingOptions)), + /* blockIndent = */ requireNonNullElse(options.blockIndent, (Integer) formattingOptionsClass.getMethod("getBlockIndent").invoke(formattingOptions)), + /* continuationIndent = */ requireNonNullElse(options.continuationIndent, (Integer) formattingOptionsClass.getMethod("getContinuationIndent").invoke(formattingOptions)), + /* removeUnusedImports = */ requireNonNullElse(options.removeUnusedImports, (Boolean) formattingOptionsClass.getMethod("getRemoveUnusedImports").invoke(formattingOptions)), /* debuggingPrintOpsAfterFormatting = */ (Boolean) formattingOptionsClass.getMethod("getDebuggingPrintOpsAfterFormatting").invoke(formattingOptions), - /* trailingCommaManagementStrategy */ Objects.requireNonNullElse(options.trailingCommaManagementStrategy, (TrailingCommaManagementStrategy) formattingOptionsClass.getMethod("getTrailingCommaManagementStrategy").invoke(formattingOptions))); + /* trailingCommaManagementStrategy */ requireNonNullElse(options.trailingCommaManagementStrategy, (TrailingCommaManagementStrategy) formattingOptionsClass.getMethod("getTrailingCommaManagementStrategy").invoke(formattingOptions))); } } diff --git a/lib/src/main/java/com/diffplug/spotless/markdown/FlexmarkStep.java b/lib/src/main/java/com/diffplug/spotless/markdown/FlexmarkStep.java index 91ac81d847..55732d8da7 100644 --- a/lib/src/main/java/com/diffplug/spotless/markdown/FlexmarkStep.java +++ b/lib/src/main/java/com/diffplug/spotless/markdown/FlexmarkStep.java @@ -15,10 +15,11 @@ */ package com.diffplug.spotless.markdown; +import static java.util.Objects.requireNonNull; + import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; -import java.util.Objects; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.FormatterStep; @@ -46,8 +47,8 @@ public static FormatterStep create(Provisioner provisioner) { /** Creates a formatter step for the given version. */ public static FormatterStep create(String version, Provisioner provisioner) { - Objects.requireNonNull(version, "version"); - Objects.requireNonNull(provisioner, "provisioner"); + requireNonNull(version, "version"); + requireNonNull(provisioner, "provisioner"); return FormatterStep.create(NAME, new FlexmarkStep(JarState.promise(() -> JarState.from(MAVEN_COORDINATE + version, provisioner))), FlexmarkStep::equalityState, 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 b08148d8c8..2f4a66fb96 100644 --- a/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java +++ b/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java @@ -16,6 +16,7 @@ package com.diffplug.spotless.markdown; import static com.diffplug.spotless.markdown.LibMarkdownPreconditions.requireKeysAndValuesNonNull; +import static java.util.Objects.requireNonNull; import java.io.Serial; import java.io.Serializable; @@ -24,7 +25,6 @@ import java.util.List; import java.util.Map; import java.util.NavigableMap; -import java.util.Objects; import java.util.TreeMap; import java.util.function.Consumer; @@ -67,9 +67,9 @@ public static FormatterStep create(Map properties, Provisioner provis /** Creates a formatter step for the given version and settings file. */ public static FormatterStep create(String version, Map properties, Provisioner provisioner) { - Objects.requireNonNull(version, "version"); - Objects.requireNonNull(properties, "properties"); - Objects.requireNonNull(provisioner, "provisioner"); + requireNonNull(version, "version"); + requireNonNull(properties, "properties"); + requireNonNull(provisioner, "provisioner"); List mavenCoordinates = new ArrayList<>(); mavenCoordinates.add(MAVEN_COORDINATE + version); 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..fb6c36cea6 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-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,19 +15,20 @@ */ package com.diffplug.spotless.markdown; +import static java.util.Objects.requireNonNull; + import java.util.Map; -import java.util.Objects; final class LibMarkdownPreconditions { // prevent direct instantiation private LibMarkdownPreconditions() {} static Map requireKeysAndValuesNonNull(Map map) { - Objects.requireNonNull(map); + requireNonNull(map); map.forEach((key, value) -> { String errorMessage = key + "=" + value; - Objects.requireNonNull(key, errorMessage); - Objects.requireNonNull(value, errorMessage); + requireNonNull(key, errorMessage); + requireNonNull(value, errorMessage); }); return map; } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java index 04c07e793f..88f0447e90 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java @@ -23,7 +23,6 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; -import java.util.Objects; import java.util.TreeMap; import javax.annotation.Nonnull; @@ -55,7 +54,7 @@ public static Map defaultDevDependenciesTypescriptWithEslint(Str dependencies.put("@typescript-eslint/eslint-plugin", "^6.1.0"); dependencies.put("@typescript-eslint/parser", "^6.1.0"); dependencies.put("typescript", "^5.1.6"); - dependencies.put("eslint", Objects.requireNonNull(eslintVersion)); + dependencies.put("eslint", requireNonNull(eslintVersion)); return dependencies; } @@ -115,8 +114,8 @@ protected void prepareNodeServerLayout(NodeServerLayout nodeServerLayout) throws } } - @Override @Nonnull + @Override public FormatterFunc createFormatterFunc() { try { logger.info("Creating formatter function (starting server)"); diff --git a/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java b/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java index 2b8c542ba8..6e259ad777 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java @@ -15,8 +15,9 @@ */ package com.diffplug.spotless.npm; +import static java.util.Objects.requireNonNull; + import java.io.File; -import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -32,7 +33,7 @@ static ExclusiveFolderAccess forFolder(@Nonnull File folder) { } static ExclusiveFolderAccess forFolder(@Nonnull String path) { - return new ExclusiveFolderAccessSharedMutex(Objects.requireNonNull(path)); + return new ExclusiveFolderAccessSharedMutex(requireNonNull(path)); } void runExclusively(ThrowingEx.Runnable runnable); @@ -44,7 +45,7 @@ final class ExclusiveFolderAccessSharedMutex implements ExclusiveFolderAccess { private final String path; private ExclusiveFolderAccessSharedMutex(@Nonnull String path) { - this.path = Objects.requireNonNull(path); + this.path = requireNonNull(path); } private Lock getMutex() { diff --git a/lib/src/main/java/com/diffplug/spotless/npm/JsonWriter.java b/lib/src/main/java/com/diffplug/spotless/npm/JsonWriter.java index ef8419b205..e216d5274c 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/JsonWriter.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/JsonWriter.java @@ -16,14 +16,14 @@ package com.diffplug.spotless.npm; import static com.diffplug.spotless.npm.JsonEscaper.jsonEscape; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.stream.Collectors.joining; import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.LinkedHashMap; import java.util.Map; -import java.util.stream.Collectors; import com.diffplug.spotless.ThrowingEx; @@ -74,7 +74,7 @@ String toJsonString() { final String valueString = valueMap.entrySet() .stream() .map(entry -> " " + jsonEscape(entry.getKey()) + ": " + jsonEscape(entry.getValue())) - .collect(Collectors.joining(",\n")); + .collect(joining(",\n")); return "{\n" + valueString + "\n}"; } @@ -89,7 +89,7 @@ void toJsonFile(File file) { } } try { - Files.write(file.toPath(), toJsonString().getBytes(StandardCharsets.UTF_8)); + Files.write(file.toPath(), toJsonString().getBytes(UTF_8)); } catch (IOException e) { throw ThrowingEx.asRuntime(e); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/ListableAdapter.java b/lib/src/main/java/com/diffplug/spotless/npm/ListableAdapter.java index aa4a96b885..123ec4a312 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/ListableAdapter.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/ListableAdapter.java @@ -15,10 +15,11 @@ */ package com.diffplug.spotless.npm; +import static java.util.Objects.requireNonNull; + import java.util.Arrays; import java.util.Iterator; import java.util.List; -import java.util.Objects; import javax.annotation.Nonnull; @@ -28,7 +29,7 @@ final class ListableAdapter implements Iterable { @SuppressWarnings("unchecked") private ListableAdapter(Object delegate) { - Objects.requireNonNull(delegate); + requireNonNull(delegate); if (!canAdapt(delegate)) { throw new IllegalArgumentException("Cannot create ListableAdapter from " + delegate.getClass() + ". Use canAdapt() to check first."); } @@ -45,14 +46,14 @@ static Iterable adapt(Object delegate) { return new ListableAdapter<>(delegate); } - @Override @Nonnull + @Override public Iterator iterator() { return delegate.iterator(); } static boolean canAdapt(Object delegate) { - Objects.requireNonNull(delegate); + requireNonNull(delegate); return delegate instanceof List || delegate.getClass().isArray(); } } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeApp.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeApp.java index 19eb584c57..c6425cda95 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeApp.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeApp.java @@ -17,8 +17,7 @@ import static com.diffplug.spotless.npm.NpmProcessFactory.OnlinePreferrence.PREFER_OFFLINE; import static com.diffplug.spotless.npm.NpmProcessFactory.OnlinePreferrence.PREFER_ONLINE; - -import java.util.Objects; +import static java.util.Objects.requireNonNull; import javax.annotation.Nonnull; @@ -46,10 +45,10 @@ public class NodeApp { protected final NpmFormatterStepLocations formatterStepLocations; public NodeApp(@Nonnull NodeServerLayout nodeServerLayout, @Nonnull NpmConfig npmConfig, @Nonnull NpmFormatterStepLocations formatterStepLocations) { - this.nodeServerLayout = Objects.requireNonNull(nodeServerLayout); - this.npmConfig = Objects.requireNonNull(npmConfig); + this.nodeServerLayout = requireNonNull(nodeServerLayout); + this.npmConfig = requireNonNull(npmConfig); this.npmProcessFactory = processFactory(formatterStepLocations); - this.formatterStepLocations = Objects.requireNonNull(formatterStepLocations); + this.formatterStepLocations = requireNonNull(formatterStepLocations); } private static NpmProcessFactory processFactory(NpmFormatterStepLocations formatterStepLocations) { diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java index ae8ff3afa8..e05c7d25e6 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java @@ -15,9 +15,10 @@ */ package com.diffplug.spotless.npm; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.util.List; -import java.util.Objects; import java.util.UUID; import javax.annotation.Nonnull; @@ -38,7 +39,7 @@ public final class NodeModulesCachingNpmProcessFactory implements NpmProcessFact private final ShadowCopy shadowCopy; private NodeModulesCachingNpmProcessFactory(@Nonnull File cacheDir) { - this.cacheDir = Objects.requireNonNull(cacheDir); + this.cacheDir = requireNonNull(cacheDir); assertDir(); // throws if cacheDir is not a directory this.shadowCopy = new ShadowCopy(this::assertDir); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmConfig.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmConfig.java index c4ea1310f8..e77685519e 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmConfig.java @@ -15,9 +15,10 @@ */ package com.diffplug.spotless.npm; +import static java.util.Objects.requireNonNull; + import java.io.Serial; import java.io.Serializable; -import java.util.Objects; import javax.annotation.Nonnull; @@ -34,7 +35,7 @@ class NpmConfig implements Serializable { private final String npmrcContent; public NpmConfig(@Nonnull String packageJsonContent, String serveScriptContent, String npmrcContent) { - this.packageJsonContent = Objects.requireNonNull(packageJsonContent); + this.packageJsonContent = requireNonNull(packageJsonContent); this.serveScriptContent = serveScriptContent; this.npmrcContent = npmrcContent; } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java index dcd79d1ee0..5494341992 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java @@ -16,6 +16,7 @@ package com.diffplug.spotless.npm; import static java.util.Objects.requireNonNull; +import static java.util.UUID.randomUUID; import java.io.File; import java.io.IOException; @@ -115,7 +116,7 @@ protected ServerProcessInfo npmRunServer() throws ServerStartException, IOExcept assertNodeServerDirReady(); LongRunningProcess server = null; try { - final UUID nodeServerInstanceId = UUID.randomUUID(); + final UUID nodeServerInstanceId = randomUUID(); // The npm process will output the randomly selected port of the http server process to 'server-.port' file // so in order to be safe, remove such a file if it exists before starting. final File serverPortFile = new File(this.nodeServerLayout.nodeModulesDir(), "server-%s.port".formatted(nodeServerInstanceId)); 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 36e94892e4..ba833ff1d6 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java @@ -15,6 +15,10 @@ */ package com.diffplug.spotless.npm; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; +import static java.util.stream.Collectors.joining; + import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -27,9 +31,7 @@ import java.security.MessageDigest; import java.time.Duration; import java.util.Arrays; -import java.util.Objects; import java.util.concurrent.TimeoutException; -import java.util.stream.Collectors; import java.util.stream.Stream; import com.diffplug.spotless.ThrowingEx; @@ -43,11 +45,11 @@ private NpmResourceHelper() { } static void writeUtf8StringToFile(File file, String stringToWrite) throws IOException { - Files.write(file.toPath(), stringToWrite.getBytes(StandardCharsets.UTF_8)); + Files.write(file.toPath(), stringToWrite.getBytes(UTF_8)); } static void writeUtf8StringToOutputStream(String stringToWrite, OutputStream outputStream) throws IOException { - final byte[] bytes = stringToWrite.getBytes(StandardCharsets.UTF_8); + final byte[] bytes = stringToWrite.getBytes(UTF_8); outputStream.write(bytes); } @@ -62,7 +64,7 @@ static void deleteFileIfExists(File file) throws IOException { static String readUtf8StringFromClasspath(Class clazz, String... resourceNames) { return Arrays.stream(resourceNames) .map(resourceName -> readUtf8StringFromClasspath(clazz, resourceName)) - .collect(Collectors.joining("\n")); + .collect(joining("\n")); } static String readUtf8StringFromClasspath(Class clazz, String resourceName) { @@ -130,7 +132,7 @@ static File copyFileToDir(File file, File targetDir) { } static File copyFileToDirAtSubpath(File file, File targetDir, String relativePath) { - Objects.requireNonNull(relativePath); + requireNonNull(relativePath); try { // create file pointing to relativePath in targetDir final Path relativeTargetFile = Path.of(targetDir.getAbsolutePath(), relativePath); @@ -148,13 +150,13 @@ static String md5(File file) { } static String md5(String fileContent, String... additionalFileContents) { - Objects.requireNonNull(fileContent, "fileContent must not be null"); + requireNonNull(fileContent, "fileContent must not be null"); Stream additionalFileContentStream = Stream.concat( Stream.of(fileContent), Stream.of(additionalFileContents)); MessageDigest md = ThrowingEx.get(() -> MessageDigest.getInstance("MD5")); - String stringToHash = additionalFileContentStream.collect(Collectors.joining(MD5_STRING_DELIMITER)); - md.update(stringToHash.getBytes(StandardCharsets.UTF_8)); + String stringToHash = additionalFileContentStream.collect(joining(MD5_STRING_DELIMITER)); + md.update(stringToHash.getBytes(UTF_8)); byte[] digest = md.digest(); // convert byte array digest to hex string diff --git a/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java index 34f8b92857..565fd7f3c5 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java @@ -82,8 +82,8 @@ private static class State extends NpmFormatterStepStateBase implements Serializ this.prettierConfig = requireNonNull(prettierConfig); } - @Override @Nonnull + @Override public FormatterFunc createFormatterFunc() { try { logger.info("creating formatter function (starting server)"); 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 02b5c8fb82..12b440f9ed 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java @@ -15,14 +15,15 @@ */ package com.diffplug.spotless.npm; +import static java.util.Collections.unmodifiableMap; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.Serial; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import javax.annotation.Nonnull; @@ -82,14 +83,14 @@ class PrettierMissingParserException extends RuntimeException implements Lint.Ha Arrays.asList(".nginx", ".nginxconf").forEach(ext -> plugins.put(ext, "prettier-plugin-nginx")); plugins.put(".sol", "prettier-plugin-solidity"); - EXTENSIONS_TO_PLUGINS = Collections.unmodifiableMap(plugins); + EXTENSIONS_TO_PLUGINS = unmodifiableMap(plugins); } private final File file; public PrettierMissingParserException(@Nonnull File file, Exception cause) { super("Prettier could not infer a parser for file '" + file + "'. Maybe you need to include a prettier plugin in devDependencies?\n\n" + recommendPlugin(file), cause); - this.file = Objects.requireNonNull(file); + this.file = requireNonNull(file); } @Override 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 eaf51320c4..f346cdd095 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/TimedLogger.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/TimedLogger.java @@ -16,9 +16,9 @@ package com.diffplug.spotless.npm; import static com.diffplug.spotless.LazyArgLogger.lazy; +import static java.util.Objects.requireNonNull; import java.util.List; -import java.util.Objects; import java.util.stream.Stream; import javax.annotation.Nonnull; @@ -42,7 +42,7 @@ final class TimedLogger { private final Ticker ticker; private TimedLogger(@Nonnull Logger logger, Ticker ticker) { - this.logger = Objects.requireNonNull(logger); + this.logger = requireNonNull(logger); this.ticker = ticker; } @@ -89,10 +89,10 @@ public static class Timed implements AutoCloseable { private final long startedAt; public Timed(@Nonnull Ticker ticker, @Nonnull String msg, @Nonnull List params, @Nonnull LogToLevelMethod delegatedLogger) { - this.ticker = Objects.requireNonNull(ticker); - this.msg = Objects.requireNonNull(msg); - this.params = List.copyOf(Objects.requireNonNull(params)); - this.delegatedLogger = Objects.requireNonNull(delegatedLogger); + this.ticker = requireNonNull(ticker); + this.msg = requireNonNull(msg); + this.params = List.copyOf(requireNonNull(params)); + this.delegatedLogger = requireNonNull(delegatedLogger); this.startedAt = ticker.read(); logStart(); } @@ -183,11 +183,11 @@ public static class TimedExec { private final Object[] args; public TimedExec(LogActiveMethod logActiveMethod, LogToLevelMethod logMethod, Ticker ticker, String message, Object... args) { - this.logActiveMethod = Objects.requireNonNull(logActiveMethod); - this.logMethod = Objects.requireNonNull(logMethod); - this.ticker = Objects.requireNonNull(ticker); - this.message = Objects.requireNonNull(message); - this.args = Objects.requireNonNull(args); + this.logActiveMethod = requireNonNull(logActiveMethod); + this.logMethod = requireNonNull(logMethod); + this.ticker = requireNonNull(ticker); + this.message = requireNonNull(message); + this.args = requireNonNull(args); } public void run(ThrowingEx.Runnable r) { diff --git a/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java index 787b14c9c9..4543b3eafe 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java @@ -90,8 +90,8 @@ public State(String stepName, Map versions, File projectDir, Fil this.inlineTsFmtSettings = inlineTsFmtSettings == null ? new TreeMap<>() : new TreeMap<>(inlineTsFmtSettings); } - @Override @Nonnull + @Override public FormatterFunc createFormatterFunc() { try { Map tsFmtOptions = unifyOptions(); diff --git a/lib/src/main/java/com/diffplug/spotless/protobuf/BufStep.java b/lib/src/main/java/com/diffplug/spotless/protobuf/BufStep.java index c499d113f7..71491ecfb3 100644 --- a/lib/src/main/java/com/diffplug/spotless/protobuf/BufStep.java +++ b/lib/src/main/java/com/diffplug/spotless/protobuf/BufStep.java @@ -15,12 +15,13 @@ */ package com.diffplug.spotless.protobuf; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.IOException; import java.io.Serializable; -import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.Objects; import java.util.regex.Pattern; import javax.annotation.Nullable; @@ -98,7 +99,7 @@ static class State implements Serializable { State(String version, ForeignExe exeAbsPath) { this.version = version; - this.exe = Objects.requireNonNull(exeAbsPath); + this.exe = requireNonNull(exeAbsPath); } String format(ProcessRunner runner, String input, File file) throws IOException, InterruptedException { @@ -106,7 +107,7 @@ String format(ProcessRunner runner, String input, File file) throws IOException, exeAbsPath = exe.confirmVersionAndGetAbsolutePath(); } List args = List.of(exeAbsPath, "format", file.getAbsolutePath()); - return runner.exec(input.getBytes(StandardCharsets.UTF_8), args).assertExitZero(StandardCharsets.UTF_8); + return runner.exec(input.getBytes(UTF_8), args).assertExitZero(UTF_8); } FormatterFunc.Closeable toFunc() { 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 3de571c889..5004894970 100644 --- a/lib/src/main/java/com/diffplug/spotless/python/BlackStep.java +++ b/lib/src/main/java/com/diffplug/spotless/python/BlackStep.java @@ -15,10 +15,11 @@ */ package com.diffplug.spotless.python; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; + import java.io.IOException; import java.io.Serializable; -import java.nio.charset.StandardCharsets; -import java.util.Objects; import java.util.regex.Pattern; import javax.annotation.Nullable; @@ -96,14 +97,14 @@ static class EqualityState implements Serializable { EqualityState(String version, ForeignExe exeAbsPath) { this.version = version; - this.exe = Objects.requireNonNull(exeAbsPath); + this.exe = requireNonNull(exeAbsPath); } String format(ProcessRunner runner, String input) throws IOException, InterruptedException { if (args == null) { args = new String[]{exe.confirmVersionAndGetAbsolutePath(), "-"}; } - return runner.exec(input.getBytes(StandardCharsets.UTF_8), args).assertExitZero(StandardCharsets.UTF_8); + return runner.exec(input.getBytes(UTF_8), args).assertExitZero(UTF_8); } FormatterFunc.Closeable toFunc() { diff --git a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterFunc.java b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterFunc.java index da3960b8f6..cfde14f5e4 100644 --- a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterFunc.java +++ b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterFunc.java @@ -15,12 +15,14 @@ */ package com.diffplug.spotless.rdf; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toList; + import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Locale; import java.util.Set; -import java.util.stream.Collectors; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.LineEnding; @@ -141,7 +143,7 @@ private static String calculateDiff(ReflectionHelper reflectionHelper, Object mo throw new RuntimeException(e); } }) - .collect(Collectors.toList()); + .collect(toList()); List onlyInAfterContent = reflectionHelper.streamGraph(graphAfter) .filter(triple -> { @@ -151,11 +153,11 @@ private static String calculateDiff(ReflectionHelper reflectionHelper, Object mo throw new RuntimeException(e); } }) - .collect(Collectors.toList()); + .collect(toList()); if (!(onlyInBeforeContent.isEmpty() && onlyInAfterContent.isEmpty())) { diffResult = onlyInBeforeContent.stream().map("< %s"::formatted) - .collect(Collectors.joining("\n")); - diffResult += "\n" + onlyInAfterContent.stream().map("> %s"::formatted).collect(Collectors.joining("\n")); + .collect(joining("\n")); + diffResult += "\n" + onlyInAfterContent.stream().map("> %s"::formatted).collect(joining("\n")); } else { diffResult = "'before' and 'after' content differs, but we don't know why. This is probably a bug."; } diff --git a/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java b/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java index 51f2aff90d..65afcbbdec 100644 --- a/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java @@ -15,6 +15,11 @@ */ package com.diffplug.spotless.rdf; +import static java.util.Comparator.comparing; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toSet; + import java.io.File; import java.io.StringWriter; import java.lang.invoke.MethodHandles; @@ -31,12 +36,10 @@ import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; -import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; -import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; @@ -298,7 +301,7 @@ private void callBuilderMethod(Object builder, Method method, String parameterVa throw new RuntimeException(ex); } }).collect( - Collectors.toList()); + toList()); if (selectedEnumValueList.isEmpty()) { throw new IllegalArgumentException( "Cannot set config option %s to value %s: value must be one of %s".formatted( @@ -311,7 +314,7 @@ private void callBuilderMethod(Object builder, Method method, String parameterVa throw new RuntimeException(ex); } }).collect( - Collectors.joining(",", "[", "]")))); + joining(",", "[", "]")))); } else if (selectedEnumValueList.size() > 1) { throw new IllegalArgumentException( "Found more than 1 enum value for name %s, that should never happen".formatted( @@ -350,7 +353,7 @@ private Object makeListOf(Type type, String parameterValueAsString) { } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { throw new RuntimeException(ex); } - }).collect(Collectors.toList()); + }).collect(toList()); } private Object makeSetOf(Type type, String parameterValueAsString) { @@ -361,7 +364,7 @@ private Object makeSetOf(Type type, String parameterValueAsString) { } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { throw new RuntimeException(ex); } - }).collect(Collectors.toSet()); + }).collect(toSet()); } private Object instantiate(Type type, String stringRepresentation) @@ -427,7 +430,7 @@ private Object getKnownPrefix(String stringRepresentation) } } throw new IllegalArgumentException("Unable to find FormattingStyle.KnownPrefix for prefix '%s'. Options are: %s".formatted(stringRepresentation, options.stream().collect( - Collectors.joining(",\n\t", "\n\t", "\n")))); + joining(",\n\t", "\n\t", "\n")))); } private static String[] split(String parameterValueAsString) { @@ -441,14 +444,14 @@ private Method getBuilderMethod(String optionName) { Method[] allMethods = TurtleFormatFormattingStyleBuilderClass.getDeclaredMethods(); List methods = Arrays.stream(allMethods).filter(m -> m.getName().equals(optionName)) .collect( - Collectors.toList()); + toList()); if (methods.isEmpty()) { List candidates = Arrays.stream(allMethods).filter(m -> m.getParameterCount() == 1) - .sorted(Comparator.comparing(Method::getName)).collect( - Collectors.toList()); + .sorted(comparing(Method::getName)).collect( + toList()); throw new RuntimeException( "Unrecognized configuration parameter name: %s. Candidates are:%n%s".formatted(optionName, candidates.stream().map(Method::getName).collect( - Collectors.joining("\n\t", "\t", "")))); + joining("\n\t", "\t", "")))); } if (methods.size() > 1) { throw new RuntimeException( @@ -506,7 +509,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl while (hasNext(resIterator)) { resources.add(next(resIterator)); } - resources.sort(Comparator.comparing(x -> { + resources.sort(comparing(x -> { try { return (String) x.getClass().getMethod("getURI").invoke(x); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { 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 e0bfa77189..bf98f1caf1 100644 --- a/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java +++ b/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java @@ -15,12 +15,13 @@ */ package com.diffplug.spotless.scala; +import static java.util.Collections.emptySet; + import java.io.File; import java.io.IOException; import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; -import java.util.Collections; import java.util.Set; import javax.annotation.Nullable; @@ -88,7 +89,7 @@ private static final class State implements Serializable { State(JarState jarState, @Nullable File configFile) throws IOException { this.jarState = jarState; - this.configSignature = FileSignature.signAsList(configFile == null ? Collections.emptySet() : Set.of(configFile)); + this.configSignature = FileSignature.signAsList(configFile == null ? emptySet() : Set.of(configFile)); } FormatterFunc createFormat() throws Exception { diff --git a/lib/src/main/java/com/diffplug/spotless/shell/ShfmtStep.java b/lib/src/main/java/com/diffplug/spotless/shell/ShfmtStep.java index 798dfb4957..4178a03d82 100644 --- a/lib/src/main/java/com/diffplug/spotless/shell/ShfmtStep.java +++ b/lib/src/main/java/com/diffplug/spotless/shell/ShfmtStep.java @@ -15,14 +15,15 @@ */ package com.diffplug.spotless.shell; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; +import static java.util.stream.Collectors.toList; + import java.io.File; import java.io.IOException; import java.io.Serializable; -import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.Objects; import java.util.regex.Pattern; -import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; @@ -111,7 +112,7 @@ static class EqualityState implements Serializable { EqualityState(String version, ForeignExe pathToExe) { this.version = version; - this.exe = Objects.requireNonNull(pathToExe); + this.exe = requireNonNull(pathToExe); } String format(ProcessRunner runner, String input, File file) throws IOException, InterruptedException { @@ -123,9 +124,9 @@ String format(ProcessRunner runner, String input, File file) throws IOException, // This will ensure that the next file name is retrieved on every format final List finalArgs = Stream.concat(args.stream(), Stream.of(file.getAbsolutePath())) - .collect(Collectors.toList()); + .collect(toList()); - return runner.exec(input.getBytes(StandardCharsets.UTF_8), finalArgs).assertExitZero(StandardCharsets.UTF_8); + return runner.exec(input.getBytes(UTF_8), finalArgs).assertExitZero(UTF_8); } FormatterFunc.Closeable toFunc() { diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java index f80b084c91..de692a5e4e 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java @@ -186,7 +186,7 @@ else if (contains(singleLineCommentStart, fChar)) { s.append(fChar); } } - return new FormatterToken(TokenType.COMMAND, word + s.toString(), start_pos); + return new FormatterToken(TokenType.COMMAND, word + s, start_pos); } if (sqlDialect.getKeywordType(word) != null) { return new FormatterToken(TokenType.KEYWORD, word, start_pos); diff --git a/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlConfig.java b/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlConfig.java index 072aa401c9..cb5c69f491 100644 --- a/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlConfig.java @@ -15,8 +15,9 @@ */ package com.diffplug.spotless.yaml; +import static java.util.Collections.unmodifiableMap; + import java.io.Serial; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; @@ -32,7 +33,7 @@ public class JacksonYamlConfig extends JacksonConfig { protected Map yamlFeatureToToggle = new LinkedHashMap<>(); public Map getYamlFeatureToToggle() { - return Collections.unmodifiableMap(yamlFeatureToToggle); + return unmodifiableMap(yamlFeatureToToggle); } /** diff --git a/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlStep.java b/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlStep.java index 36b10fa061..d7f5a420aa 100644 --- a/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlStep.java +++ b/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlStep.java @@ -15,11 +15,12 @@ */ package com.diffplug.spotless.yaml; +import static java.util.Objects.requireNonNull; + import java.io.Serial; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.util.Objects; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.FormatterStep; @@ -53,8 +54,8 @@ public static String defaultVersion() { public static FormatterStep create(JacksonYamlConfig jacksonConfig, String jacksonVersion, Provisioner provisioner) { - Objects.requireNonNull(jacksonConfig, "jacksonConfig cannot be null"); - Objects.requireNonNull(provisioner, "provisioner cannot be null"); + requireNonNull(jacksonConfig, "jacksonConfig cannot be null"); + requireNonNull(provisioner, "provisioner cannot be null"); return FormatterStep.create(NAME, new JacksonYamlStep(JarState.promise(() -> JarState.from(MAVEN_COORDINATE + jacksonVersion, provisioner)), jacksonConfig), JacksonYamlStep::equalityState, diff --git a/lib/src/test/java/com/diffplug/spotless/JarStateTest.java b/lib/src/test/java/com/diffplug/spotless/JarStateTest.java index 8b3d84fc18..a45aede55b 100644 --- a/lib/src/test/java/com/diffplug/spotless/JarStateTest.java +++ b/lib/src/test/java/com/diffplug/spotless/JarStateTest.java @@ -15,6 +15,9 @@ */ package com.diffplug.spotless; +import static java.util.stream.Collectors.toSet; +import static org.assertj.core.api.SoftAssertions.assertSoftly; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -25,9 +28,7 @@ import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; -import java.util.stream.Collectors; -import org.assertj.core.api.SoftAssertions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -42,7 +43,7 @@ class JarStateTest { File b; - Provisioner provisioner = (withTransitives, deps) -> deps.stream().map(name -> name.equals("a") ? a : b).collect(Collectors.toSet()); + Provisioner provisioner = (withTransitives, deps) -> deps.stream().map(name -> name.equals("a") ? a : b).collect(toSet()); @BeforeEach void setUp() throws IOException { @@ -62,7 +63,7 @@ void itCreatesClassloaderWhenForcedClassLoaderNotSet() throws IOException { JarState state1 = JarState.from(a.getName(), provisioner); JarState state2 = JarState.from(b.getName(), provisioner); - SoftAssertions.assertSoftly(softly -> { + assertSoftly(softly -> { softly.assertThat(state1.getClassLoader()).isNotNull(); softly.assertThat(state2.getClassLoader()).isNotNull(); }); @@ -75,7 +76,7 @@ void itReturnsForcedClassloaderIfSetNoMatterIfSetBeforeOrAfterCreation() throws JarState.setForcedClassLoader(forcedClassLoader); JarState stateB = JarState.from(b.getName(), provisioner); - SoftAssertions.assertSoftly(softly -> { + assertSoftly(softly -> { softly.assertThat(stateA.getClassLoader()).isSameAs(forcedClassLoader); softly.assertThat(stateB.getClassLoader()).isSameAs(forcedClassLoader); }); @@ -91,7 +92,7 @@ void itReturnsForcedClassloaderEvenWhenRountripSerialized() throws IOException, JarState stateARoundtripSerialized = roundtripSerialize(stateA); JarState stateBRoundtripSerialized = roundtripSerialize(stateB); - SoftAssertions.assertSoftly(softly -> { + assertSoftly(softly -> { softly.assertThat(stateARoundtripSerialized.getClassLoader()).isSameAs(forcedClassLoader); softly.assertThat(stateBRoundtripSerialized.getClassLoader()).isSameAs(forcedClassLoader); }); diff --git a/lib/src/test/java/com/diffplug/spotless/LineEndingTest.java b/lib/src/test/java/com/diffplug/spotless/LineEndingTest.java index e84d660758..3394598b0d 100644 --- a/lib/src/test/java/com/diffplug/spotless/LineEndingTest.java +++ b/lib/src/test/java/com/diffplug/spotless/LineEndingTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,11 +15,12 @@ */ package com.diffplug.spotless; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.IOException; import java.io.Reader; import java.io.StringReader; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class LineEndingTest { @@ -44,7 +45,7 @@ void testGetEndingFor() throws IOException { static void assertLineEnding(String ending, String input) throws IOException { try (Reader reader = new StringReader(input)) { - Assertions.assertEquals(ending, LineEnding.PreserveLineEndingPolicy.getEndingFor(reader)); + assertEquals(ending, LineEnding.PreserveLineEndingPolicy.getEndingFor(reader)); } } } diff --git a/lib/src/test/java/com/diffplug/spotless/LintSuppressionTest.java b/lib/src/test/java/com/diffplug/spotless/LintSuppressionTest.java index 1e1037a6ef..d34ea7edab 100644 --- a/lib/src/test/java/com/diffplug/spotless/LintSuppressionTest.java +++ b/lib/src/test/java/com/diffplug/spotless/LintSuppressionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,9 @@ */ package com.diffplug.spotless; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; @@ -39,7 +39,7 @@ private LintState dummyLintState() { private Formatter formatter() { return Formatter.builder() .lineEndingsPolicy(LineEnding.UNIX.createPolicy()) - .encoding(StandardCharsets.UTF_8) + .encoding(UTF_8) .steps(List.of(EndWithNewlineStep.create())) .build(); } diff --git a/lib/src/test/java/com/diffplug/spotless/RingBufferByteArrayOutputStreamTest.java b/lib/src/test/java/com/diffplug/spotless/RingBufferByteArrayOutputStreamTest.java index 18427723f7..c452ede3df 100644 --- a/lib/src/test/java/com/diffplug/spotless/RingBufferByteArrayOutputStreamTest.java +++ b/lib/src/test/java/com/diffplug/spotless/RingBufferByteArrayOutputStreamTest.java @@ -15,11 +15,12 @@ */ package com.diffplug.spotless; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.stream.Stream; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -29,85 +30,85 @@ class RingBufferByteArrayOutputStreamTest { private final byte[] bytes = new byte[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; - @ParameterizedTest(name = "{index} writeStrategy: {0}") @MethodSource("writeStrategies") + @ParameterizedTest(name = "{index} writeStrategy: {0}") void toStringBehavesNormallyWithinLimit(String name, ByteWriteStrategy writeStrategy) { RingBufferByteArrayOutputStream stream = new RingBufferByteArrayOutputStream(12, 1); writeStrategy.write(stream, bytes); - Assertions.assertThat(stream.toString()).isEqualTo("0123456789"); + assertThat(stream.toString()).isEqualTo("0123456789"); } - @ParameterizedTest(name = "{index} writeStrategy: {0}") @MethodSource("writeStrategies") + @ParameterizedTest(name = "{index} writeStrategy: {0}") void toStringBehavesOverwritingOverLimit(String name, ByteWriteStrategy writeStrategy) { RingBufferByteArrayOutputStream stream = new RingBufferByteArrayOutputStream(4, 1); writeStrategy.write(stream, bytes); - Assertions.assertThat(stream.toString()).hasSize(4); - Assertions.assertThat(stream.toString()).isEqualTo("6789"); + assertThat(stream.toString()).hasSize(4); + assertThat(stream.toString()).isEqualTo("6789"); } - @ParameterizedTest(name = "{index} writeStrategy: {0}") @MethodSource("writeStrategies") + @ParameterizedTest(name = "{index} writeStrategy: {0}") void toStringBehavesNormallyAtExactlyLimit(String name, ByteWriteStrategy writeStrategy) { RingBufferByteArrayOutputStream stream = new RingBufferByteArrayOutputStream(bytes.length, 1); writeStrategy.write(stream, bytes); - Assertions.assertThat(stream.toString()).isEqualTo("0123456789"); + assertThat(stream.toString()).isEqualTo("0123456789"); } - @ParameterizedTest(name = "{index} writeStrategy: {0}") @MethodSource("writeStrategies") + @ParameterizedTest(name = "{index} writeStrategy: {0}") void toByteArrayBehavesNormallyWithinLimit(String name, ByteWriteStrategy writeStrategy) { RingBufferByteArrayOutputStream stream = new RingBufferByteArrayOutputStream(12, 1); writeStrategy.write(stream, bytes); - Assertions.assertThat(stream.toByteArray()).isEqualTo(bytes); + assertThat(stream.toByteArray()).isEqualTo(bytes); } - @ParameterizedTest(name = "{index} writeStrategy: {0}") @MethodSource("writeStrategies") + @ParameterizedTest(name = "{index} writeStrategy: {0}") void toByteArrayBehavesOverwritingOverLimit(String name, ByteWriteStrategy writeStrategy) { RingBufferByteArrayOutputStream stream = new RingBufferByteArrayOutputStream(4, 1); writeStrategy.write(stream, bytes); - Assertions.assertThat(stream.toByteArray()).hasSize(4); - Assertions.assertThat(stream.toByteArray()).isEqualTo(new byte[]{'6', '7', '8', '9'}); + assertThat(stream.toByteArray()).hasSize(4); + assertThat(stream.toByteArray()).isEqualTo(new byte[]{'6', '7', '8', '9'}); } - @ParameterizedTest(name = "{index} writeStrategy: {0}") @MethodSource("writeStrategies") + @ParameterizedTest(name = "{index} writeStrategy: {0}") void toByteArrayBehavesOverwritingAtExactlyLimit(String name, ByteWriteStrategy writeStrategy) { RingBufferByteArrayOutputStream stream = new RingBufferByteArrayOutputStream(bytes.length, 1); writeStrategy.write(stream, bytes); - Assertions.assertThat(stream.toByteArray()).isEqualTo(bytes); + assertThat(stream.toByteArray()).isEqualTo(bytes); } - @ParameterizedTest(name = "{index} writeStrategy: {0}") @MethodSource("writeStrategies") + @ParameterizedTest(name = "{index} writeStrategy: {0}") void writeToBehavesNormallyWithinLimit(String name, ByteWriteStrategy writeStrategy) throws IOException { RingBufferByteArrayOutputStream stream = new RingBufferByteArrayOutputStream(12, 1); writeStrategy.write(stream, bytes); ByteArrayOutputStream target = new ByteArrayOutputStream(); stream.writeTo(target); - Assertions.assertThat(target.toByteArray()).isEqualTo(bytes); + assertThat(target.toByteArray()).isEqualTo(bytes); } - @ParameterizedTest(name = "{index} writeStrategy: {0}") @MethodSource("writeStrategies") + @ParameterizedTest(name = "{index} writeStrategy: {0}") void writeToBehavesOverwritingOverLimit(String name, ByteWriteStrategy writeStrategy) throws IOException { RingBufferByteArrayOutputStream stream = new RingBufferByteArrayOutputStream(4, 1); writeStrategy.write(stream, bytes); ByteArrayOutputStream target = new ByteArrayOutputStream(); stream.writeTo(target); - Assertions.assertThat(target.toByteArray()).hasSize(4); - Assertions.assertThat(target.toByteArray()).isEqualTo(new byte[]{'6', '7', '8', '9'}); + assertThat(target.toByteArray()).hasSize(4); + assertThat(target.toByteArray()).isEqualTo(new byte[]{'6', '7', '8', '9'}); } - @ParameterizedTest(name = "{index} writeStrategy: {0}") @MethodSource("writeStrategies") + @ParameterizedTest(name = "{index} writeStrategy: {0}") void writeToBehavesNormallyAtExactlyLimit(String name, ByteWriteStrategy writeStrategy) throws IOException { RingBufferByteArrayOutputStream stream = new RingBufferByteArrayOutputStream(bytes.length, 1); writeStrategy.write(stream, bytes); ByteArrayOutputStream target = new ByteArrayOutputStream(); stream.writeTo(target); - Assertions.assertThat(target.toByteArray()).isEqualTo(bytes); + assertThat(target.toByteArray()).isEqualTo(bytes); } @Test @@ -116,8 +117,8 @@ void writeToBehavesCorrectlyWhenOverLimitMultipleCalls() { RingBufferByteArrayOutputStream stream = new RingBufferByteArrayOutputStream(2, 1); stream.write('0'); stream.write(new byte[]{'1', '2'}, 0, 2); - Assertions.assertThat(stream.toString()).hasSize(2); - Assertions.assertThat(stream.toString()).isEqualTo("12"); + assertThat(stream.toString()).hasSize(2); + assertThat(stream.toString()).isEqualTo("12"); } private static Stream writeStrategies() { diff --git a/lib/src/test/java/com/diffplug/spotless/npm/NodeServerLayoutTest.java b/lib/src/test/java/com/diffplug/spotless/npm/NodeServerLayoutTest.java index 229435eb21..d9b37f7f24 100644 --- a/lib/src/test/java/com/diffplug/spotless/npm/NodeServerLayoutTest.java +++ b/lib/src/test/java/com/diffplug/spotless/npm/NodeServerLayoutTest.java @@ -15,11 +15,11 @@ */ package com.diffplug.spotless.npm; +import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; -import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.Test; @@ -31,7 +31,7 @@ class NodeServerLayoutTest extends ResourceHarness { @Test void itCalculatesSameNodeModulesDirForSameContent() throws IOException { File testDir = newFolder("build"); - String packageJsonContent = prettierPackageJson(Collections.emptyMap()); + String packageJsonContent = prettierPackageJson(emptyMap()); String serveJsContent = "fun main() { console.log('Hello, world!'); }"; NodeServerLayout layout1 = new NodeServerLayout(testDir, packageJsonContent, serveJsContent); NodeServerLayout layout2 = new NodeServerLayout(testDir, packageJsonContent, serveJsContent); @@ -55,7 +55,7 @@ void itCalculatesDifferentNodeModulesDirForDifferentPackageJson() throws IOExcep @Test void itCalculatesDifferentNodeModulesDirForDifferentServeJs() throws IOException { File testDir = newFolder("build"); - String packageJsonContent = prettierPackageJson(Collections.emptyMap()); + String packageJsonContent = prettierPackageJson(emptyMap()); String serveJsContent1 = "fun main() { console.log('Hello, world!'); }"; String serveJsContent2 = "fun main() { console.log('Goodbye, world!'); }"; 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 132afe362e..e97541a5a9 100644 --- a/lib/src/test/java/com/diffplug/spotless/npm/TimedLoggerTest.java +++ b/lib/src/test/java/com/diffplug/spotless/npm/TimedLoggerTest.java @@ -18,12 +18,13 @@ import static com.diffplug.spotless.npm.TimedLogger.MESSAGE_PREFIX_BEGIN; import static com.diffplug.spotless.npm.TimedLogger.MESSAGE_PREFIX_END; import static com.diffplug.spotless.npm.TimedLogger.MESSAGE_SUFFIX_TOOK; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Arrays; import java.util.LinkedList; import java.util.List; -import org.assertj.core.api.Assertions; import org.assertj.core.api.Condition; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -115,14 +116,14 @@ void itLogsBeginAndEndPrefixes() { @Test void itThrowsExceptionsInChecked() { - Assertions.assertThatThrownBy(() -> timedLogger.withInfo("This should be logged").runChecked(() -> { + assertThatThrownBy(() -> timedLogger.withInfo("This should be logged").runChecked(() -> { throw new Exception("This is an exception"); })).isInstanceOf(Exception.class).hasMessage("This is an exception"); } @Test void itLogsEvenWhenExceptionsAreThrown() { - Assertions.assertThatThrownBy(() -> timedLogger.withInfo("This should be logged").run(() -> { + assertThatThrownBy(() -> timedLogger.withInfo("This should be logged").run(() -> { testTicker.tickMillis(2); throw new Exception("This is an exception"); })).isInstanceOf(RuntimeException.class) @@ -141,7 +142,7 @@ void itReturnsValueOfCallableWhileStillLogging() { return "This is the result"; }); - Assertions.assertThat(result).isEqualTo("This is the result"); + assertThat(result).isEqualTo("This is the result"); testLogger.assertEvents(2); testLogger.assertHasEventWithMessageAndArguments(MESSAGE_PREFIX_BEGIN); @@ -192,16 +193,16 @@ public List getEvents() { } public void assertNoEvents() { - Assertions.assertThat(getEvents()).isEmpty(); + assertThat(getEvents()).isEmpty(); } public void assertEvents(int eventCount) { - Assertions.assertThat(getEvents()).hasSize(eventCount); + assertThat(getEvents()).hasSize(eventCount); } public void assertHasEventWithMessageAndArguments(String message, Object... arguments) { - Assertions.assertThat(getEvents()).haveAtLeastOne(new Condition<>(event -> { + assertThat(getEvents()).haveAtLeastOne(new Condition<>(event -> { if (!event.msg().contains(message)) { return false; } diff --git a/lib/src/testCompatCleanthat2Dot1/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java b/lib/src/testCompatCleanthat2Dot1/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java index 2f3cdc9646..97ef69778a 100644 --- a/lib/src/testCompatCleanthat2Dot1/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java +++ b/lib/src/testCompatCleanthat2Dot1/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.glue.java; -import org.assertj.core.api.Assertions; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; import eu.solven.cleanthat.engine.java.refactorer.JavaRefactorer; @@ -23,6 +24,6 @@ public class JavaCleanthatRefactorerFuncTest { @Test public void testMutatorsDetection() { - Assertions.assertThat(JavaRefactorer.getAllIncluded()).isNotEmpty(); + assertThat(JavaRefactorer.getAllIncluded()).isNotEmpty(); } } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/Antlr4Extension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/Antlr4Extension.java index 02795af355..dab46f1a1e 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/Antlr4Extension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/Antlr4Extension.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package com.diffplug.gradle.spotless; -import java.util.Objects; +import static java.util.Objects.requireNonNull; import javax.inject.Inject; @@ -44,7 +44,7 @@ public class Antlr4FormatterConfig { private final String version; Antlr4FormatterConfig(String version) { - this.version = Objects.requireNonNull(version); + this.version = requireNonNull(version); addStep(createStep()); } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseGroovyExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseGroovyExtension.java index 230445740b..79557ea8a7 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseGroovyExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseGroovyExtension.java @@ -16,10 +16,10 @@ package com.diffplug.gradle.spotless; import static com.diffplug.gradle.spotless.PluginGradlePreconditions.requireElementsNonNull; +import static java.util.Objects.requireNonNull; import java.util.List; import java.util.Map; -import java.util.Objects; import org.gradle.api.Project; @@ -38,7 +38,7 @@ public void importOrder(String... importOrder) { } public void importOrderFile(Object importOrderFile) { - Objects.requireNonNull(importOrderFile); + requireNonNull(importOrderFile); addStep(ImportOrderStep.forGroovy().createFrom(getProject().file(importOrderFile))); } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseKotlinExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseKotlinExtension.java index 975be992c2..6e746f8a30 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseKotlinExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseKotlinExtension.java @@ -15,12 +15,14 @@ */ package com.diffplug.gradle.spotless; +import static java.util.Collections.emptyList; +import static java.util.Collections.emptyMap; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.io.IOException; -import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.function.Consumer; import javax.annotation.Nullable; @@ -53,7 +55,7 @@ public KtlintConfig ktlint() throws IOException { /** Adds the specified version of ktlint. */ public KtlintConfig ktlint(String version) throws IOException { - return new KtlintConfig(version, Collections.emptyMap(), Collections.emptyList()); + return new KtlintConfig(version, emptyMap(), emptyList()); } /** Uses the ktfmt jar to format source code. */ @@ -76,7 +78,7 @@ public final class DiktatConfig { private FileSignature config; private DiktatConfig(String version) { - Objects.requireNonNull(version, "version"); + requireNonNull(version, "version"); this.version = version; addStep(createStep()); } @@ -104,8 +106,8 @@ public final class KtfmtConfig { private KtfmtStep.KtfmtFormattingOptions options; private KtfmtConfig(String version) { - Objects.requireNonNull(version); - this.version = Objects.requireNonNull(version); + requireNonNull(version); + this.version = requireNonNull(version); addStep(createStep()); } @@ -159,7 +161,7 @@ private KtlintConfig( String version, Map editorConfigOverride, List customRuleSets) throws IOException { - Objects.requireNonNull(version); + requireNonNull(version); File defaultEditorConfig = getProject().getRootProject().file(".editorconfig"); FileSignature editorConfigPath = defaultEditorConfig.exists() ? FileSignature.signAsList(defaultEditorConfig) : null; this.version = version; diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FlexmarkExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FlexmarkExtension.java index d1f941613b..25bb03a267 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FlexmarkExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FlexmarkExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package com.diffplug.gradle.spotless; -import java.util.Objects; +import static java.util.Objects.requireNonNull; import javax.inject.Inject; @@ -52,7 +52,7 @@ public class FlexmarkFormatterConfig { private final String version; FlexmarkFormatterConfig(String version) { - this.version = Objects.requireNonNull(version); + this.version = requireNonNull(version); addStep(createStep()); } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FreshMarkExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FreshMarkExtension.java index 71904b2bb4..c26eb9225e 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FreshMarkExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FreshMarkExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,11 @@ package com.diffplug.gradle.spotless; import static com.diffplug.gradle.spotless.PluginGradlePreconditions.requireElementsNonNull; +import static java.util.Objects.requireNonNull; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.TreeMap; import javax.inject.Inject; @@ -42,7 +42,7 @@ public FreshMarkExtension(SpotlessExtension spotless) { } public void properties(Action> action) { - propertyActions.add(Objects.requireNonNull(action)); + propertyActions.add(requireNonNull(action)); } public void propertiesFile(Object... files) { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GitRatchetGradle.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GitRatchetGradle.java index c58f0d39c4..80f9681c27 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GitRatchetGradle.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GitRatchetGradle.java @@ -121,8 +121,7 @@ protected File getDir(File project) { return project; } - @Override - protected @Nullable File getParent(File project) { + @Nullable protected @Override File getParent(File project) { return project.getParentFile(); } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java index e76e1e8350..cb58241601 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java @@ -16,6 +16,7 @@ package com.diffplug.gradle.spotless; import static com.diffplug.gradle.spotless.PluginGradlePreconditions.requireElementsNonNull; +import static java.util.Objects.requireNonNull; import java.io.File; import java.util.ArrayList; @@ -24,7 +25,6 @@ import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Set; import javax.inject.Inject; @@ -68,7 +68,7 @@ public ImportOrderConfig importOrder(String... importOrder) { } public ImportOrderConfig importOrderFile(Object importOrderFile) { - Objects.requireNonNull(importOrderFile); + requireNonNull(importOrderFile); return new ImportOrderConfig(getProject().file(importOrderFile)); } @@ -174,7 +174,7 @@ public GoogleJavaFormatConfig googleJavaFormat() { * for a workaround for using snapshot versions. */ public GoogleJavaFormatConfig googleJavaFormat(String version) { - Objects.requireNonNull(version); + requireNonNull(version); return new GoogleJavaFormatConfig(version); } @@ -187,20 +187,20 @@ public class GoogleJavaFormatConfig { boolean formatJavadoc = true; GoogleJavaFormatConfig(String version) { - this.version = Objects.requireNonNull(version); + this.version = requireNonNull(version); this.groupArtifact = GoogleJavaFormatStep.defaultGroupArtifact(); this.style = GoogleJavaFormatStep.defaultStyle(); addStep(createStep()); } public GoogleJavaFormatConfig groupArtifact(String groupArtifact) { - this.groupArtifact = Objects.requireNonNull(groupArtifact); + this.groupArtifact = requireNonNull(groupArtifact); replaceStep(createStep()); return this; } public GoogleJavaFormatConfig style(String style) { - this.style = Objects.requireNonNull(style); + this.style = requireNonNull(style); replaceStep(createStep()); return this; } @@ -259,7 +259,7 @@ public PalantirJavaFormatConfig palantirJavaFormat() { * for a workaround for using snapshot versions. */ public PalantirJavaFormatConfig palantirJavaFormat(String version) { - Objects.requireNonNull(version); + requireNonNull(version); return new PalantirJavaFormatConfig(version); } @@ -269,13 +269,13 @@ public class PalantirJavaFormatConfig { boolean formatJavadoc; PalantirJavaFormatConfig(String version) { - this.version = Objects.requireNonNull(version); + this.version = requireNonNull(version); this.style = PalantirJavaFormatStep.defaultStyle(); addStep(createStep()); } public PalantirJavaFormatConfig style(String style) { - this.style = Objects.requireNonNull(style); + this.style = requireNonNull(style); replaceStep(createStep()); return this; } @@ -386,14 +386,14 @@ public class FormatAnnotationsConfig { } public FormatAnnotationsConfig addTypeAnnotation(String simpleName) { - Objects.requireNonNull(simpleName); + requireNonNull(simpleName); addedTypeAnnotations.add(simpleName); replaceStep(createStep()); return this; } public FormatAnnotationsConfig removeTypeAnnotation(String simpleName) { - Objects.requireNonNull(simpleName); + requireNonNull(simpleName); removedTypeAnnotations.add(simpleName); replaceStep(createStep()); return this; @@ -429,21 +429,21 @@ public class CleanthatJavaConfig { } public CleanthatJavaConfig groupArtifact(String groupArtifact) { - Objects.requireNonNull(groupArtifact); + requireNonNull(groupArtifact); this.groupArtifact = groupArtifact; replaceStep(createStep()); return this; } public CleanthatJavaConfig version(String version) { - Objects.requireNonNull(version); + requireNonNull(version); this.version = version; replaceStep(createStep()); return this; } public CleanthatJavaConfig sourceCompatibility(String jdkVersion) { - Objects.requireNonNull(jdkVersion); + requireNonNull(jdkVersion); this.sourceJdk = jdkVersion; replaceStep(createStep()); return this; diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PluginGradlePreconditions.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PluginGradlePreconditions.java index eb23f39c4e..41a440e7ea 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PluginGradlePreconditions.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PluginGradlePreconditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package com.diffplug.gradle.spotless; -import java.util.Objects; +import static java.util.Objects.requireNonNull; final class PluginGradlePreconditions { // prevent direct instantiation @@ -23,17 +23,17 @@ private PluginGradlePreconditions() {} @SafeVarargs static T[] requireElementsNonNull(T... elements) { - Objects.requireNonNull(elements); + requireNonNull(elements); for (T element : elements) { - Objects.requireNonNull(element); + requireNonNull(element); } return elements; } static > I requireElementsNonNull(I elements) { - Objects.requireNonNull(elements); + requireNonNull(elements); for (Object element : elements) { - Objects.requireNonNull(element); + requireNonNull(element); } return elements; } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PomExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PomExtension.java index 4fd92c1f02..9a56d0ada1 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PomExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PomExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package com.diffplug.gradle.spotless; -import java.util.Objects; +import static java.util.Objects.requireNonNull; import javax.inject.Inject; @@ -46,7 +46,7 @@ public SortPomGradleConfig sortPom() { } public SortPomGradleConfig sortPom(String version) { - Objects.requireNonNull(version); + requireNonNull(version); return new SortPomGradleConfig(version); } @@ -59,7 +59,7 @@ public class SortPomGradleConfig { SortPomGradleConfig(String version) { this(); - cfg.version = Objects.requireNonNull(version); + cfg.version = requireNonNull(version); } public SortPomGradleConfig encoding(String encoding) { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ProtobufExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ProtobufExtension.java index 7b0a6bb30a..3129e4ec08 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ProtobufExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ProtobufExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2022-2023 DiffPlug + * Copyright 2022-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,7 @@ package com.diffplug.gradle.spotless; import static com.diffplug.spotless.protobuf.ProtobufConstants.LICENSE_HEADER_DELIMITER; - -import java.util.Objects; +import static java.util.Objects.requireNonNull; import javax.inject.Inject; @@ -53,7 +52,7 @@ protected void setupTask(SpotlessTask task) { /** Adds the specified version of buf. */ public BufFormatExtension buf(String version) { - Objects.requireNonNull(version); + requireNonNull(version); return new BufFormatExtension(version); } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java index 33aded8bdd..2b1ec09799 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,10 @@ */ package com.diffplug.gradle.spotless; +import static java.nio.charset.StandardCharsets.UTF_8; + import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @@ -88,7 +89,7 @@ public File getUnitOutput() { @TaskAction public void trivialFunction() throws IOException { Files.createParentDirs(unitOutput); - Files.write(Integer.toString(1), unitOutput, StandardCharsets.UTF_8); + Files.write(Integer.toString(1), unitOutput, UTF_8); } // this field is stupid, but we need it, see https://github.com/diffplug/spotless/issues/1260 diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ScalaExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ScalaExtension.java index 1639f3473c..73444c6423 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ScalaExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ScalaExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,9 @@ */ package com.diffplug.gradle.spotless; +import static java.util.Objects.requireNonNull; + import java.io.File; -import java.util.Objects; import javax.annotation.Nullable; import javax.inject.Inject; @@ -44,24 +45,22 @@ public ScalaFmtConfig scalafmt(String version) { public class ScalaFmtConfig { final String version; - @Nullable - String scalaMajorVersion; - @Nullable - Object configFile; + @Nullable String scalaMajorVersion; + @Nullable Object configFile; ScalaFmtConfig(String version) { - this.version = Objects.requireNonNull(version); + this.version = requireNonNull(version); addStep(createStep()); } public ScalaFmtConfig configFile(Object configFile) { - this.configFile = Objects.requireNonNull(configFile); + this.configFile = requireNonNull(configFile); replaceStep(createStep()); return this; } public ScalaFmtConfig scalaMajorVersion(String scalaMajorVersion) { - this.scalaMajorVersion = Objects.requireNonNull(scalaMajorVersion); + this.scalaMajorVersion = requireNonNull(scalaMajorVersion); replaceStep(createStep()); return this; } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ShellExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ShellExtension.java index 6a21f2ffb4..97c44a48ca 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ShellExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ShellExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package com.diffplug.gradle.spotless; -import java.util.Objects; +import static java.util.Objects.requireNonNull; import javax.inject.Inject; @@ -43,7 +43,7 @@ protected void setupTask(SpotlessTask task) { /** Adds the specified version of shfmt. */ public ShfmtExtension shfmt(String version) { - Objects.requireNonNull(version); + requireNonNull(version); return new ShfmtExtension(version); } 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 a029bd00d4..9eddde320d 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 @@ -40,8 +40,8 @@ public SpotlessTask getSource() { return source; } - @TaskAction @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") + @TaskAction public void performAction() throws IOException { Path srcRoot = getProject().getProjectDir().toPath(); Path diagnoseRoot = getProject().getLayout().getBuildDirectory().getAsFile().get() 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 2ff4896d9e..8f7205c724 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 @@ -15,10 +15,10 @@ */ package com.diffplug.gradle.spotless; +import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.Map; @@ -73,7 +73,7 @@ public void setLineEndings(LineEnding lineEndings) { this.lineEndings = requireNonNull(lineEndings); } - Charset encoding = StandardCharsets.UTF_8; + Charset encoding = UTF_8; /** Returns the encoding to use. */ public Charset getEncoding() { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java index 713c9a2e86..7afbfd3afb 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java @@ -15,12 +15,13 @@ */ package com.diffplug.gradle.spotless; +import static java.util.Objects.requireNonNull; + import java.io.File; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Locale; -import java.util.Objects; import org.eclipse.jgit.lib.ObjectId; import org.gradle.api.DefaultTask; @@ -58,7 +59,7 @@ public String getEncoding() { } public void setEncoding(String encoding) { - this.encoding = Objects.requireNonNull(encoding); + this.encoding = requireNonNull(encoding); } protected Provider lineEndingsPolicy = null; @@ -127,7 +128,7 @@ public ObjectId getRatchetSha() { protected List lintSuppressions = new ArrayList<>(); public void setLintSuppressions(List lintSuppressions) { - this.lintSuppressions = Objects.requireNonNull(lintSuppressions); + this.lintSuppressions = requireNonNull(lintSuppressions); } @Input @@ -137,9 +138,9 @@ public List getLintSuppressions() { protected FileCollection target; - @PathSensitive(PathSensitivity.RELATIVE) @Incremental @InputFiles + @PathSensitive(PathSensitivity.RELATIVE) public FileCollection getTarget() { return target; } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskService.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskService.java index 33347f8dfc..49ff679d1d 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskService.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskService.java @@ -15,8 +15,9 @@ */ package com.diffplug.gradle.spotless; +import static java.util.Collections.synchronizedMap; + import java.io.File; -import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; @@ -53,9 +54,9 @@ * apply already did). */ public abstract class SpotlessTaskService implements BuildService, AutoCloseable, OperationCompletionListener { - private final Map apply = Collections.synchronizedMap(new HashMap<>()); - private final Map source = Collections.synchronizedMap(new HashMap<>()); - private final Map provisioner = Collections.synchronizedMap(new HashMap<>()); + private final Map apply = synchronizedMap(new HashMap<>()); + private final Map source = synchronizedMap(new HashMap<>()); + private final Map provisioner = synchronizedMap(new HashMap<>()); @Nullable GradleProvisioner.DedupingProvisioner predeclaredProvisioner; 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 0d5838c24a..0b3b9a91d3 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 @@ -15,12 +15,11 @@ */ package com.diffplug.gradle.spotless; +import static java.util.Collections.emptyMap; import static java.util.Objects.requireNonNull; import java.util.Arrays; -import java.util.Collections; import java.util.Map; -import java.util.Objects; import java.util.TreeMap; import javax.annotation.Nullable; @@ -70,7 +69,7 @@ public TypescriptFormatExtension tsfmt(Map devDependencies) { public class TypescriptFormatExtension extends NpmStepConfig { - private Map config = Collections.emptyMap(); + private Map config = emptyMap(); @Nullable TsConfigFileType configFileType = null; @@ -80,7 +79,7 @@ public class TypescriptFormatExtension extends NpmStepConfig devDependencies) { super(getProject(), TypescriptExtension.this::replaceStep); - this.devDependencies = Objects.requireNonNull(devDependencies); + this.devDependencies = requireNonNull(devDependencies); } public TypescriptFormatExtension config(final Map config) { diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ConfigAvoidanceTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ConfigAvoidanceTest.java index bd521bd864..9bee90f667 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ConfigAvoidanceTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ConfigAvoidanceTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,10 @@ */ package com.diffplug.gradle.spotless; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.IOException; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; class ConfigAvoidanceTest extends GradleIntegrationHarness { @@ -52,8 +53,8 @@ void noConfigOnHelp() throws IOException { setFile("src/main/java/test.java").toResource("java/googlejavaformat/JavaCodeUnformatted.test"); String help = gradleRunner().withArguments("help").build().getOutput(); - Assertions.assertThat(help).doesNotContain("Canary was configured"); + assertThat(help).doesNotContain("Canary was configured"); String check = gradleRunner().withArguments("check").buildAndFail().getOutput(); - Assertions.assertThat(check).contains("Canary was configured", "Canary ran", "Execution failed for task ':spotlessJavaCheck'"); + assertThat(check).contains("Canary was configured", "Canary ran", "Execution failed for task ':spotlessJavaCheck'"); } } 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 a942d6a9e8..883b277222 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 @@ -15,14 +15,15 @@ */ package com.diffplug.gradle.spotless; +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.List; -import org.assertj.core.api.Assertions; import org.gradle.api.Project; import org.gradle.api.provider.Provider; import org.gradle.api.services.BuildServiceParameters; @@ -62,7 +63,7 @@ private SpotlessTaskImpl createFormatTask(String name) { SpotlessTaskImpl task = project.getTasks().create("spotless" + SpotlessPlugin.capitalize(name), SpotlessTaskImpl.class); task.init(taskService); task.setLineEndingsPolicy(project.provider(LineEnding.UNIX::createPolicy)); - task.setTarget(Collections.singletonList(file)); + task.setTarget(singletonList(file)); return task; } @@ -109,11 +110,11 @@ private void assertCheckFailure(Bundle spotless, String... expectedLines) throws String firstLine = "The following files had format violations:\n"; String lastLine = "\n" + EXPECTED_RUN_SPOTLESS_APPLY_SUGGESTION; - Assertions.assertThat(msg).startsWith(firstLine).endsWith(lastLine); + assertThat(msg).startsWith(firstLine).endsWith(lastLine); String middle = msg.substring(firstLine.length(), msg.length() - lastLine.length()); String expectedMessage = StringPrinter.buildStringFromLines(expectedLines); - Assertions.assertThat(middle).isEqualTo(expectedMessage.substring(0, expectedMessage.length() - 1)); + assertThat(middle).isEqualTo(expectedMessage.substring(0, expectedMessage.length() - 1)); } static final String EXPECTED_RUN_SPOTLESS_APPLY_SUGGESTION = FileSignature.machineIsWin() @@ -144,7 +145,7 @@ void customRunToFixMessage() throws Exception { String firstLine = "The following files had format violations:\n"; String lastLine = "\n" + customMessage; - Assertions.assertThat(msg).startsWith(firstLine).endsWith(lastLine); + assertThat(msg).startsWith(firstLine).endsWith(lastLine); } @Test 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 ebd4bcbbf2..9ce5f75e39 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 @@ -59,8 +59,8 @@ void passesIfNoException() throws Exception { expectSuccess(); } - @Test - @EnabledForJreRange(max = JAVA_23) // `[Incubating] Problems report is available at` presents in the output from Java 24 or above. + @EnabledForJreRange(max = JAVA_23) + @Test // `[Incubating] Problems report is available at` presents in the output from Java 24 or above. void anyExceptionShouldFail() throws Exception { writeBuild( " } // format", @@ -108,8 +108,8 @@ void unlessExemptedByPath() throws Exception { expectSuccess(); } - @Test - @EnabledForJreRange(max = JAVA_23) // `[Incubating] Problems report is available at` presents in the output from Java 24 or above. + @EnabledForJreRange(max = JAVA_23) + @Test // `[Incubating] Problems report is available at` presents in the output from Java 24 or above. void failsIfNeitherStepNorFileExempted() throws Exception { writeBuild( " ignoreErrorForStep 'nope'", diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FilePermissionsTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FilePermissionsTest.java index d342348a5b..98d131b27b 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FilePermissionsTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FilePermissionsTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2023 DiffPlug + * Copyright 2020-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.diffplug.gradle.spotless; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.condition.OS.WINDOWS; import java.io.IOException; @@ -23,13 +24,12 @@ import java.nio.file.attribute.PosixFilePermissions; import org.assertj.core.api.AbstractStringAssert; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledOnOs; class FilePermissionsTest extends GradleIntegrationHarness { - @Test @DisabledOnOs(WINDOWS) + @Test void spotlessApplyShouldPreservePermissions() throws IOException { setFile("build.gradle").toLines( "plugins {", @@ -55,6 +55,6 @@ void spotlessApplyShouldPreservePermissions() throws IOException { } private AbstractStringAssert assertPermissions(Path path) throws IOException { - return Assertions.assertThat(PosixFilePermissions.toString(Files.getPosixFilePermissions(path))); + return assertThat(PosixFilePermissions.toString(Files.getPosixFilePermissions(path))); } } 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 0a6cb2c466..5004ed0656 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 @@ -15,10 +15,11 @@ */ package com.diffplug.gradle.spotless; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.File; import java.io.IOException; -import org.assertj.core.api.Assertions; import org.gradle.api.Project; import org.gradle.api.file.ConfigurableFileTree; import org.junit.jupiter.api.BeforeEach; @@ -43,7 +44,7 @@ void absolutePathDoesntWork() throws IOException { File someFile = setFile("someFolder/someFile").toContent(""); File someFolder = someFile.getParentFile(); fileTree.exclude(someFolder.getAbsolutePath()); - Assertions.assertThat(fileTree).containsExactlyInAnyOrder(someFile); + assertThat(fileTree).containsExactlyInAnyOrder(someFile); } @Test @@ -51,6 +52,6 @@ void relativePathDoes() throws IOException { File someFile = setFile("someFolder/someFile").toContent(""); File someFolder = someFile.getParentFile(); fileTree.exclude(LintSuppression.relativizeAsUnix(rootFolder(), someFolder)); - Assertions.assertThat(fileTree).containsExactlyInAnyOrder(); + assertThat(fileTree).containsExactlyInAnyOrder(); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FreshMarkExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FreshMarkExtensionTest.java index 95a3286e5e..c58eb8f238 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FreshMarkExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FreshMarkExtensionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,8 +23,8 @@ import org.junit.jupiter.api.condition.EnabledForJreRange; class FreshMarkExtensionTest extends GradleIntegrationHarness { - @Test @EnabledForJreRange(max = JAVA_14) + @Test void integration() throws IOException { setFile("build.gradle").toLines( "plugins {", diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GitRatchetGradleTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GitRatchetGradleTest.java index e4c1d31615..d9d0a80797 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GitRatchetGradleTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GitRatchetGradleTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,12 +15,13 @@ */ package com.diffplug.gradle.spotless; +import static java.util.Objects.requireNonNull; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.IOException; import java.util.Date; -import java.util.Objects; import java.util.TimeZone; -import org.assertj.core.api.Assertions; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.NoFilepatternException; @@ -197,9 +198,9 @@ void multiProject(int useConfigCache) throws Exception { ObjectId cleanFolder = TreeWalk.forPath(git.getRepository(), "clean", baseline.getTree()).getObjectId(0); ObjectId dirtyFolder = TreeWalk.forPath(git.getRepository(), "dirty", baseline.getTree()).getObjectId(0); - Assertions.assertThat(baseline.getTree().toObjectId()).isEqualTo(ObjectId.fromString(BASELINE_ROOT)); - Assertions.assertThat(cleanFolder).isEqualTo(ObjectId.fromString(BASELINE_CLEAN)); - Assertions.assertThat(dirtyFolder).isEqualTo(ObjectId.fromString(BASELINE_DIRTY)); + assertThat(baseline.getTree().toObjectId()).isEqualTo(ObjectId.fromString(BASELINE_ROOT)); + assertThat(cleanFolder).isEqualTo(ObjectId.fromString(BASELINE_CLEAN)); + assertThat(dirtyFolder).isEqualTo(ObjectId.fromString(BASELINE_DIRTY)); assertPass("spotlessCheck") .outcome(":spotlessCheck", TaskOutcome.SUCCESS) @@ -231,7 +232,7 @@ void multiProject(int useConfigCache) throws Exception { .outcome(":added:spotlessMisc", TaskOutcome.UP_TO_DATE); RevCommit next = addAndCommit(git); - Assertions.assertThat(next.getTree().toObjectId()).isNotEqualTo(baseline.getTree().toObjectId()); + assertThat(next.getTree().toObjectId()).isNotEqualTo(baseline.getTree().toObjectId()); // if we commit to main (the baseline), then tasks will be out of date only because the baseline changed // TO REPEAAT: // - everything was up-to-date @@ -240,8 +241,8 @@ void multiProject(int useConfigCache) throws Exception { ObjectId nextCleanFolder = TreeWalk.forPath(git.getRepository(), "clean", next.getTree()).getObjectId(0); ObjectId nextDirtyFolder = TreeWalk.forPath(git.getRepository(), "dirty", next.getTree()).getObjectId(0); - Assertions.assertThat(nextCleanFolder).isEqualTo(cleanFolder); // the baseline for 'clean' didn't change - Assertions.assertThat(nextDirtyFolder).isNotEqualTo(dirtyFolder); // only the baseline for dirty + assertThat(nextCleanFolder).isEqualTo(cleanFolder); // the baseline for 'clean' didn't change + assertThat(nextDirtyFolder).isNotEqualTo(dirtyFolder); // only the baseline for dirty // check will still pass, but the tasks are all out of date assertPass("spotlessCheck") @@ -256,14 +257,14 @@ public static class BuildResultAssertion { BuildResult result; BuildResultAssertion(BuildResult result) { - this.result = Objects.requireNonNull(result); + this.result = requireNonNull(result); } public BuildResultAssertion outcome(String taskPath, TaskOutcome expected) { TaskOutcome actual = result.getTasks().stream() .filter(task -> task.getPath().equals(taskPath)) .findAny().get().getOutcome(); - Assertions.assertThat(actual).isEqualTo(expected); + assertThat(actual).isEqualTo(expected); return this; } } 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 e26c6cc148..7c38e5a7f0 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 @@ -15,6 +15,7 @@ */ package com.diffplug.gradle.spotless; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; @@ -25,7 +26,6 @@ import java.util.TreeSet; import org.assertj.core.api.AbstractStringAssert; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import com.diffplug.common.base.Errors; @@ -130,7 +130,7 @@ private void checkRanAgainst(String... ranAgainst) throws IOException { private AbstractStringAssert checkRanAgainstNoneButError() throws IOException { String console = taskRanAgainst("spotlessCheck"); - return Assertions.assertThat(console); + return assertThat(console); } private String taskRanAgainst(String task, String... ranAgainst) throws IOException { 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 aeb34e8572..a2b5d9737d 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 @@ -16,6 +16,7 @@ package com.diffplug.gradle.spotless; import static com.diffplug.common.base.Strings.isNullOrEmpty; +import static java.util.stream.Collectors.toList; import static org.junit.jupiter.api.Assertions.fail; import java.io.File; @@ -24,7 +25,6 @@ import java.util.ListIterator; import java.util.function.BiConsumer; import java.util.function.Predicate; -import java.util.stream.Collectors; import org.gradle.api.provider.Provider; import org.gradle.testkit.runner.BuildResult; @@ -160,7 +160,7 @@ public void iterateFiles(Predicate subpathsToInclude, BiConsumer treeDef = TreeDef.forFile(Errors.rethrow()); List files = TreeStream.depthFirst(treeDef, rootFolder()) .filter(File::isFile) - .collect(Collectors.toList()); + .collect(toList()); ListIterator iterator = files.listIterator(files.size()); int rootLength = rootFolder().getAbsolutePath().length() + 1; @@ -211,13 +211,13 @@ private void taskIsUpToDate(String task, boolean upToDate) throws IOException { public static List outcomes(BuildResult build, TaskOutcome outcome) { return build.taskPaths(outcome).stream() .filter(s -> !s.equals(":spotlessInternalRegisterDependencies")) - .collect(Collectors.toList()); + .collect(toList()); } public static List outcomes(BuildResult build) { return build.getTasks().stream() .filter(t -> !t.getPath().equals(":spotlessInternalRegisterDependencies")) - .collect(Collectors.toList()); + .collect(toList()); } static String buildResultToString(BuildResult result) { 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 e94d269644..b4fe8fd730 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-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ class GroovyGradleExtensionTest extends GroovyExtensionTest { private static final String HEADER = "//My tests header"; @ParameterizedTest - @ValueSource(booleans = {true, false}) + @ValueSource(booleans = {false, true}) void testTarget(boolean useDefaultTarget) throws IOException { String target = useDefaultTarget ? "" : "target 'other.gradle'"; String buildContent = StringPrinter.buildStringFromLines( 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 da2cf86440..650d8c00ce 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 @@ -15,13 +15,14 @@ */ package com.diffplug.gradle.spotless; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.File; import java.io.IOException; import java.io.Writer; -import java.nio.charset.StandardCharsets; import java.util.stream.Stream; -import org.assertj.core.api.Assertions; import org.gradle.testkit.runner.GradleRunner; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInstance; @@ -57,13 +58,13 @@ void before() throws IOException { " }", "}"); dirty = new File(rootFolder(), "DIRTY.md"); - Files.write("ABC".getBytes(StandardCharsets.UTF_8), dirty); + Files.write("ABC".getBytes(UTF_8), dirty); clean = new File(rootFolder(), "CLEAN.md"); - Files.write("abc".getBytes(StandardCharsets.UTF_8), clean); + Files.write("abc".getBytes(UTF_8), clean); diverge = new File(rootFolder(), "DIVERGE.md"); - Files.write("ABC".getBytes(StandardCharsets.UTF_8), diverge); + Files.write("ABC".getBytes(UTF_8), diverge); outofbounds = new File(rootFolder(), "OUTOFBOUNDS.md"); - Files.write("ABC".getBytes(StandardCharsets.UTF_8), outofbounds); + Files.write("ABC".getBytes(UTF_8), outofbounds); } private static Stream configurationCacheProvider() { @@ -103,43 +104,43 @@ protected GradleRunner gradleRunner(boolean configurationCache) throws IOExcepti } } - @ParameterizedTest @MethodSource("configurationCacheProvider") + @ParameterizedTest void dirty(boolean configurationCache) throws IOException { runWith(configurationCache, "spotlessApply", "--quiet", "-PspotlessIdeHook=" + dirty.getAbsolutePath(), "-PspotlessIdeHookUseStdOut"); - Assertions.assertThat(output).isEqualTo("abc"); - Assertions.assertThat(error).startsWith("IS DIRTY"); + assertThat(output).isEqualTo("abc"); + assertThat(error).startsWith("IS DIRTY"); } - @ParameterizedTest @MethodSource("configurationCacheProvider") + @ParameterizedTest void clean(boolean configurationCache) throws IOException { runWith(configurationCache, "spotlessApply", "--quiet", "-PspotlessIdeHook=" + clean.getAbsolutePath(), "-PspotlessIdeHookUseStdOut"); - Assertions.assertThat(output).isEmpty(); - Assertions.assertThat(error).startsWith("IS CLEAN"); + assertThat(output).isEmpty(); + assertThat(error).startsWith("IS CLEAN"); } - @ParameterizedTest @MethodSource("configurationCacheProvider") + @ParameterizedTest void diverge(boolean configurationCache) throws IOException { runWith(configurationCache, "spotlessApply", "--quiet", "-PspotlessIdeHook=" + diverge.getAbsolutePath(), "-PspotlessIdeHookUseStdOut"); - Assertions.assertThat(output).isEmpty(); - Assertions.assertThat(error).startsWith("DID NOT CONVERGE"); + assertThat(output).isEmpty(); + assertThat(error).startsWith("DID NOT CONVERGE"); } - @ParameterizedTest @MethodSource("configurationCacheProvider") + @ParameterizedTest void outofbounds(boolean configurationCache) throws IOException { runWith(configurationCache, "spotlessApply", "--quiet", "-PspotlessIdeHook=" + outofbounds.getAbsolutePath(), "-PspotlessIdeHookUseStdOut"); - Assertions.assertThat(output).isEmpty(); - Assertions.assertThat(error).isEmpty(); + assertThat(output).isEmpty(); + assertThat(error).isEmpty(); } - @ParameterizedTest @MethodSource("configurationCacheProvider") + @ParameterizedTest void notAbsolute(boolean configurationCache) throws IOException { runWith(configurationCache, "spotlessApply", "--quiet", "-PspotlessIdeHook=build.gradle", "-PspotlessIdeHookUseStdOut"); - Assertions.assertThat(output).isEmpty(); - Assertions.assertThat(error).contains("Argument passed to spotlessIdeHook must be an absolute path"); + assertThat(output).isEmpty(); + assertThat(error).contains("Argument passed to spotlessIdeHook must be an absolute path"); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IndentIntegrationTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IndentIntegrationTest.java index 38457faae9..155b17b6b5 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IndentIntegrationTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IndentIntegrationTest.java @@ -36,14 +36,14 @@ void oldIndentApiLogsDeprecationWarning(String indentationMethodName) throws IOE } @ParameterizedTest - @ValueSource(strings = {"leadingTabsToSpaces", "leadingSpacesToTabs"}) + @ValueSource(strings = {"leadingSpacesToTabs", "leadingTabsToSpaces"}) void newIndentApiDoesNotLogDeprecationWarning(String indentationMethodName) throws IOException { BuildResult result = runIndentFormatter(indentationMethodName); assertThat(result.getOutput()).doesNotContainPattern(".*" + indentationMethodName + ".*deprecated.*"); } - @ParameterizedTest(name = "{0}") @MethodSource("indentationCombinations") + @ParameterizedTest(name = "{0}") void indentationCombinations(String testName, String indentationMethodName, String actualResource, String expectedResultResource) throws IOException { runIndentFormatter(indentationMethodName, actualResource); assertFile("test.txt").sameAsResource(expectedResultResource); 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..f3d479686c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,10 @@ */ package com.diffplug.gradle.spotless; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.IOException; -import org.assertj.core.api.Assertions; import org.gradle.testkit.runner.BuildResult; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -35,8 +36,8 @@ private static String styleGuideMapString(String styleGuideName) { return EslintStyleGuide.fromNameOrNull(styleGuideName).asGradleMapStringMergedWith(EslintFormatterStep.defaultDevDependencies()); } - @NpmTest @Nested + @NpmTest class EslintGeneralJavascriptTests extends GradleIntegrationHarness { @Test void supportsEslintFormattingForJavascript() throws IOException { @@ -126,7 +127,7 @@ void eslintRequiresAnExplicitEslintConfig() throws IOException { "}"); setFile("test.js").toResource("npm/eslint/javascript/styleguide/standard/javascript-es6.dirty"); BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").buildAndFail(); - Assertions.assertThat(spotlessApply.getOutput()).contains("ESLint must be configured"); + assertThat(spotlessApply.getOutput()).contains("ESLint must be configured"); } @Test @@ -156,8 +157,8 @@ void eslintAllowsSpecifyingCustomLibraryVersions() throws IOException { } - @NpmTest @Nested + @NpmTest class EslintPopularJsStyleGuideTests extends GradleIntegrationHarness { @ParameterizedTest(name = "{index}: eslint can be applied using styleguide {0}") @ValueSource(strings = {"airbnb", "google", "standard", "xo"}) @@ -183,8 +184,8 @@ void formattingUsingStyleguide(String styleguide) throws Exception { } } - @NpmTest @Nested + @NpmTest class JavascriptPrettierTests extends GradleIntegrationHarness { @Test void supportsPrettierFormattingForJavascript() throws IOException { diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/KotlinGradleExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/KotlinGradleExtensionTest.java index c607c36912..866c71c6a3 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/KotlinGradleExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/KotlinGradleExtensionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ class KotlinGradleExtensionTest extends KotlinExtensionTest { @ParameterizedTest - @ValueSource(booleans = {true, false}) + @ValueSource(booleans = {false, true}) void testTarget(boolean useDefaultTarget) throws IOException { setFile("build.gradle").toLines( "plugins {", diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/MultiProjectAfterEvaluate.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/MultiProjectAfterEvaluate.java index 1e31c6a2ab..b35771aad4 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/MultiProjectAfterEvaluate.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/MultiProjectAfterEvaluate.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,10 @@ */ package com.diffplug.gradle.spotless; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.IOException; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; /** Reproduces https://github.com/diffplug/spotless/issues/506 */ @@ -34,6 +35,6 @@ void failureDoesntTriggerAll() throws IOException { "repositories { mavenCentral() }", "spotless { java { googleJavaFormat() } }"); String output = gradleRunner().withArguments("spotlessApply", "--warning-mode", "all").build().getOutput().replace("\r\n", "\n"); - Assertions.assertThat(output).doesNotContain("Using method Project#afterEvaluate(Action) when the project is already evaluated has been deprecated."); + assertThat(output).doesNotContain("Using method Project#afterEvaluate(Action) when the project is already evaluated has been deprecated."); } } 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 69301327c7..d186aff078 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 @@ -15,9 +15,10 @@ */ package com.diffplug.gradle.spotless; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.IOException; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import com.diffplug.common.base.StringPrinter; @@ -87,7 +88,7 @@ public void predeclaredFails() throws IOException { "}", "spotless { predeclareDeps() }"); createNSubprojects(); - Assertions.assertThat(gradleRunner().withArguments("spotlessApply").buildAndFail().getOutput()) + assertThat(gradleRunner().withArguments("spotlessApply").buildAndFail().getOutput()) .contains("Add a step with [com.google.googlejavaformat:google-java-format:1.17.0] into the `spotlessPredeclare` block in the root project."); } @@ -133,7 +134,7 @@ public void predeclaredOrdering() throws IOException { "}", "spotless { predeclareDepsFromBuildscript() }"); createNSubprojects(); - Assertions.assertThat(gradleRunner().withArguments("spotlessApply").buildAndFail().getOutput()) + assertThat(gradleRunner().withArguments("spotlessApply").buildAndFail().getOutput()) .contains("Could not find method spotlessPredeclare() for arguments"); } @@ -148,7 +149,7 @@ public void predeclaredUndeclared() throws IOException { " java { googleJavaFormat('1.17.0') }", "}"); createNSubprojects(); - Assertions.assertThat(gradleRunner().withArguments("spotlessApply").buildAndFail().getOutput()) + assertThat(gradleRunner().withArguments("spotlessApply").buildAndFail().getOutput()) .contains("Could not find method spotlessPredeclare() for arguments"); } } 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 46d0817fcd..69264f7dc1 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 @@ -16,12 +16,12 @@ package com.diffplug.gradle.spotless; import static com.diffplug.gradle.spotless.FormatExtension.NpmStepConfig.SPOTLESS_NPM_INSTALL_CACHE_DEFAULT_NAME; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; import java.nio.file.Path; -import org.assertj.core.api.Assertions; import org.gradle.testkit.runner.BuildResult; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; @@ -33,8 +33,8 @@ import com.diffplug.common.base.Errors; import com.diffplug.spotless.tag.NpmTest; -@TestMethodOrder(OrderAnnotation.class) @NpmTest +@TestMethodOrder(OrderAnnotation.class) class NpmInstallCacheIntegrationTests extends GradleIntegrationHarness { static File pertainingCacheDir; @@ -51,7 +51,7 @@ void prettierCachesNodeModulesToADefaultFolderWhenCachingEnabled() throws IOExce File dir1 = newFolder("npm-prettier-1"); File cacheDir = DEFAULT_DIR_FOR_NPM_INSTALL_CACHE_DO_NEVER_WRITE_TO_THIS; BuildResult result = runPhpPrettierOnDir(dir1, cacheDir); - Assertions.assertThat(result.getOutput()) + assertThat(result.getOutput()) .doesNotContain("Using cached node_modules for") .contains("Caching node_modules for ") .contains(Path.of(dir1.getAbsolutePath(), "build", SPOTLESS_NPM_INSTALL_CACHE_DEFAULT_NAME).toString()); @@ -63,39 +63,39 @@ void prettierCachesAndReusesNodeModulesInSpecificInstallCacheFolder() throws IOE File dir1 = newFolder("npm-prettier-1"); File cacheDir = newFolder("npm-prettier-cache"); BuildResult result = runPhpPrettierOnDir(dir1, cacheDir); - Assertions.assertThat(result.getOutput()).doesNotContainPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E"); + assertThat(result.getOutput()).doesNotContainPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E"); File dir2 = newFolder("npm-prettier-2"); BuildResult result2 = runPhpPrettierOnDir(dir2, cacheDir); - Assertions.assertThat(result2.getOutput()).containsPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E"); + assertThat(result2.getOutput()).containsPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E"); } @Test void prettierDoesNotCacheNodeModulesIfNotExplicitlyEnabled() throws IOException { File dir2 = newFolder("npm-prettier-1"); BuildResult result = runPhpPrettierOnDir(dir2, null); - Assertions.assertThat(result.getOutput()) + assertThat(result.getOutput()) .doesNotContainPattern("Using cached node_modules for .*") .doesNotContainPattern("Caching node_modules for .*"); } - @Test @Order(1) + @Test void prettierCachesNodeModuleInGlobalInstallCacheDir() throws IOException { File dir1 = newFolder("npm-prettier-global-1"); File cacheDir = pertainingCacheDir; BuildResult result = runPhpPrettierOnDir(dir1, cacheDir); - Assertions.assertThat(result.getOutput()) + assertThat(result.getOutput()) .doesNotContainPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E") .containsPattern("Caching node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E"); } - @Test @Order(2) + @Test void prettierUsesCachedNodeModulesFromGlobalInstallCacheDir() throws IOException { File dir2 = newFolder("npm-prettier-global-2"); File cacheDir = pertainingCacheDir; BuildResult result = runPhpPrettierOnDir(dir2, cacheDir); - Assertions.assertThat(result.getOutput()) + assertThat(result.getOutput()) .containsPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E") .doesNotContainPattern("Caching node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E"); } @@ -122,29 +122,29 @@ private BuildResult runPhpPrettierOnDir(File projDir, File cacheDir) throws IOEx "}"); setFile(baseDir + "/php-example.php").toResource("npm/prettier/plugins/php.dirty"); final BuildResult spotlessApply = gradleRunner().withProjectDir(projDir).withArguments("--stacktrace", "--info", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); assertFile(baseDir + "/php-example.php").sameAsResource("npm/prettier/plugins/php.clean"); return spotlessApply; } - @Test @Order(3) + @Test void tsfmtCachesNodeModuleInGlobalInstallCacheDir() throws IOException { File dir1 = newFolder("npm-tsfmt-global-1"); File cacheDir = pertainingCacheDir; BuildResult result = runTsfmtOnDir(dir1, cacheDir); - Assertions.assertThat(result.getOutput()) + assertThat(result.getOutput()) .doesNotContainPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E") .containsPattern("Caching node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E"); } - @Test @Order(4) + @Test void tsfmtUsesCachedNodeModulesFromGlobalInstallCacheDir() throws IOException { File dir2 = newFolder("npm-tsfmt-global-2"); File cacheDir = pertainingCacheDir; BuildResult result = runTsfmtOnDir(dir2, cacheDir); - Assertions.assertThat(result.getOutput()) + assertThat(result.getOutput()) .containsPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E") .doesNotContainPattern("Caching node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E"); } @@ -153,7 +153,7 @@ void tsfmtUsesCachedNodeModulesFromGlobalInstallCacheDir() throws IOException { void tsfmtDoesNotCacheNodeModulesIfNotExplicitlyEnabled() throws IOException { File dir2 = newFolder("npm-tsfmt-1"); BuildResult result = runTsfmtOnDir(dir2, null); - Assertions.assertThat(result.getOutput()) + assertThat(result.getOutput()) .doesNotContainPattern("Using cached node_modules for .*") .doesNotContainPattern("Caching node_modules for .*"); } @@ -181,24 +181,24 @@ private BuildResult runTsfmtOnDir(File projDir, File cacheDir) throws IOExceptio return spotlessApply; } - @Test @Order(5) + @Test void eslintCachesNodeModuleInGlobalInstallCacheDir() throws IOException { File dir1 = newFolder("npm-eslint-global-1"); File cacheDir = pertainingCacheDir; BuildResult result = runEslintOnDir(dir1, cacheDir); - Assertions.assertThat(result.getOutput()) + assertThat(result.getOutput()) .doesNotContainPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E") .containsPattern("Caching node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E"); } - @Test @Order(6) + @Test void eslintUsesCachedNodeModulesFromGlobalInstallCacheDir() throws IOException { File dir2 = newFolder("npm-eslint-global-2"); File cacheDir = pertainingCacheDir; BuildResult result = runEslintOnDir(dir2, cacheDir); - Assertions.assertThat(result.getOutput()) + assertThat(result.getOutput()) .containsPattern("Using cached node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E") .doesNotContainPattern("Caching node_modules for .*\\Q" + cacheDir.getAbsolutePath() + "\\E"); } @@ -208,7 +208,7 @@ void eslintDoesNotCacheNodeModulesIfNotExplicitlyEnabled() throws IOException { File dir2 = newFolder("npm-eslint-1"); File cacheDir = null; BuildResult result = runEslintOnDir(dir2, cacheDir); - Assertions.assertThat(result.getOutput()) + assertThat(result.getOutput()) .doesNotContainPattern("Using cached node_modules for .*") .doesNotContainPattern("Caching node_modules for .*"); } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/NpmTestsWithoutNpmInstallationTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/NpmTestsWithoutNpmInstallationTest.java index 6abbc108fa..7e157e1d67 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/NpmTestsWithoutNpmInstallationTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/NpmTestsWithoutNpmInstallationTest.java @@ -15,7 +15,8 @@ */ package com.diffplug.gradle.spotless; -import org.assertj.core.api.Assertions; +import static org.assertj.core.api.Assertions.assertThat; + import org.gradle.testkit.runner.BuildResult; import org.junit.jupiter.api.Test; @@ -58,7 +59,7 @@ void useNodeAndNpmFromNodeGradlePlugin() throws Exception { gradleRunner().withArguments("nodeSetup", "npmSetup").build(); // then run spotless using that node installation final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("test.ts").sameAsResource("npm/prettier/config/typescript.configfile_prettier_2.clean"); } catch (Exception e) { printContents(); @@ -78,7 +79,7 @@ void useNodeAndNpmFromNodeGradlePlugin_example1() throws Exception { setFile("build.gradle").toResource("com/diffplug/gradle/spotless/NpmTestsWithoutNpmInstallationTest_gradle_node_plugin_example_1.gradle"); setFile("test.ts").toResource("npm/prettier/config/typescript.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("test.ts").sameAsResource("npm/prettier/config/typescript.configfile_prettier_2.clean"); } catch (Exception e) { printContents(); @@ -92,7 +93,7 @@ void useNpmFromNodeGradlePlugin_example2() throws Exception { setFile("build.gradle").toResource("com/diffplug/gradle/spotless/NpmTestsWithoutNpmInstallationTest_gradle_node_plugin_example_2.gradle"); setFile("test.ts").toResource("npm/prettier/config/typescript.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("test.ts").sameAsResource("npm/prettier/config/typescript.configfile_prettier_2.clean"); } catch (Exception e) { printContents(); @@ -131,7 +132,7 @@ void useNpmFromNodeGradlePlugin() throws Exception { gradleRunner().withArguments("nodeSetup", "npmSetup").build(); // then run spotless using that node installation final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("test.ts").sameAsResource("npm/prettier/config/typescript.configfile_prettier_2.clean"); } catch (Exception e) { printContents(); @@ -170,7 +171,7 @@ void useNpmNextToConfiguredNodePluginFromNodeGradlePlugin() throws Exception { gradleRunner().withArguments("nodeSetup", "npmSetup").build(); // then run spotless using that node installation final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("test.ts").sameAsResource("npm/prettier/config/typescript.configfile_prettier_2.clean"); } catch (Exception e) { printContents(); @@ -185,7 +186,7 @@ public void supportsConfigurationCache() throws Exception { BuildResult spotlessApply = gradleRunner() .withGradleVersion(GradleVersionSupport.STABLE_CONFIGURATION_CACHE.version) .withArguments("--stacktrace", "--configuration-cache", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("test.ts").sameAsResource("npm/prettier/config/typescript.configfile_prettier_2.clean"); } } 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 888f11f294..c99618bae3 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-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,18 +15,19 @@ */ package com.diffplug.gradle.spotless; +import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.IOException; import java.util.Arrays; -import java.util.Collections; import java.util.List; import org.gradle.api.Project; import org.gradle.api.provider.Provider; import org.gradle.api.services.BuildServiceParameters; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.diffplug.common.base.StringPrinter; @@ -69,7 +70,7 @@ private SpotlessTaskImpl createFormatTask(String name, FormatterStep step) { task.init(taskService); task.setSteps(List.of(step)); task.setLineEndingsPolicy(project.provider(LineEnding.UNIX::createPolicy)); - task.setTarget(Collections.singletonList(file)); + task.setTarget(singletonList(file)); return task; } @@ -206,9 +207,9 @@ void diagnose() throws Exception { private void assertFolderContents(String subfolderName, String... files) throws IOException { File subfolder = new File(rootFolder(), subfolderName); - Assertions.assertTrue(subfolder.isDirectory()); + assertTrue(subfolder.isDirectory()); String asList = String.join("\n", Arrays.asList(files)); - Assertions.assertEquals(StringPrinter.buildStringFromLines(files).trim(), asList); + assertEquals(StringPrinter.buildStringFromLines(files).trim(), asList); } @Test @@ -235,6 +236,6 @@ void paddedCellCheckConvergeFailureMsg() throws IOException { private void assertFailureMessage(Bundle bundle, String... expectedOutput) { String msg = bundle.checkFailureMsg(); String expected = StringPrinter.buildStringFromLines(expectedOutput).trim(); - Assertions.assertEquals(expected, msg); + assertEquals(expected, msg); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java index 9b6edf526a..6fd2a94a09 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java @@ -15,9 +15,10 @@ */ package com.diffplug.gradle.spotless; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.IOException; -import org.assertj.core.api.Assertions; import org.gradle.testkit.runner.BuildResult; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -51,7 +52,7 @@ void useInlineConfig(String prettierVersion) throws IOException { "}"); setFile("test.ts").toResource("npm/prettier/config/typescript.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); if (PRETTIER_VERSION_2.equals(prettierVersion)) { assertFile("test.ts").sameAsResource("npm/prettier/config/typescript.configfile_prettier_2.clean"); } else if (PRETTIER_VERSION_3.equals(prettierVersion)) { @@ -78,7 +79,7 @@ void verifyCleanSpotlessCheckWorks(String prettierVersion) throws IOException { "}"); setFile("test.ts").toResource("npm/prettier/config/typescript.dirty"); final BuildResult spotlessCheckFailsGracefully = gradleRunner().withArguments("--stacktrace", "spotlessCheck").buildAndFail(); - Assertions.assertThat(spotlessCheckFailsGracefully.getOutput()).contains("> The following files had format violations:"); + assertThat(spotlessCheckFailsGracefully.getOutput()).contains("> The following files had format violations:"); gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); gradleRunner().withArguments("--stacktrace", "spotlessCheck").build(); @@ -101,7 +102,7 @@ void useFileConfig(String prettierVersion) throws IOException { "}"); setFile("test.ts").toResource("npm/prettier/config/typescript.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); if (PRETTIER_VERSION_2.equals(prettierVersion)) { assertFile("test.ts").sameAsResource("npm/prettier/config/typescript.configfile_prettier_2.clean"); } else if (PRETTIER_VERSION_3.equals(prettierVersion)) { @@ -125,7 +126,7 @@ void chooseParserBasedOnFilename(String prettierVersion) throws IOException { "}"); setFile("dirty.json").toResource("npm/prettier/filename/dirty.json"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("dirty.json").sameAsResource("npm/prettier/filename/clean.json"); } @@ -160,7 +161,7 @@ void useJavaCommunityPlugin(String prettierVersion) throws IOException { "}"); setFile("JavaTest.java").toResource("npm/prettier/plugins/java-test.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("JavaTest.java").sameAsResource("npm/prettier/plugins/java-test.clean"); } @@ -190,7 +191,7 @@ void useJavaCommunityPluginFileConfig(String prettierVersion) throws IOException "}"); setFile("JavaTest.java").toResource("npm/prettier/plugins/java-test.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("JavaTest.java").sameAsResource("npm/prettier/plugins/java-test.clean"); } @@ -214,8 +215,8 @@ void suggestsMissingJavaCommunityPlugin(String prettierVersion) throws IOExcepti "}"); setFile("JavaTest.java").toResource("npm/prettier/plugins/java-test.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").buildAndFail(); - Assertions.assertThat(spotlessApply.getOutput()).contains("Could not infer a parser"); - Assertions.assertThat(spotlessApply.getOutput()).contains("prettier-plugin-java"); + assertThat(spotlessApply.getOutput()).contains("Could not infer a parser"); + assertThat(spotlessApply.getOutput()).contains("prettier-plugin-java"); } @ParameterizedTest(name = "{index}: usePhpCommunityPlugin with prettier {0}") @@ -249,7 +250,7 @@ void usePhpCommunityPlugin(String prettierVersion) throws IOException { "}"); setFile("php-example.php").toResource("npm/prettier/plugins/php.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("php-example.php").sameAsResource("npm/prettier/plugins/php.clean"); } @@ -306,9 +307,9 @@ void usePhpAndJavaCommunityPlugin(String prettierVersion) throws IOException { setFile("php-example.php").toResource("npm/prettier/plugins/php.dirty"); setFile("JavaTest.java").toResource("npm/prettier/plugins/java-test.dirty"); final BuildResult spotlessApply = gradleRunner().forwardOutput().withArguments("--stacktrace", "--info", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); final BuildResult spotlessApply2 = gradleRunner().forwardOutput().withArguments("--stacktrace", "--info", "spotlessApply").build(); - Assertions.assertThat(spotlessApply2.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply2.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("php-example.php").sameAsResource("npm/prettier/plugins/php.clean"); assertFile("JavaTest.java").sameAsResource("npm/prettier/plugins/java-test.clean"); } @@ -337,7 +338,7 @@ void autodetectNpmrcFileConfig(String prettierVersion) throws IOException { "}"); setFile("test.ts").toResource("npm/prettier/config/typescript.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").buildAndFail(); - Assertions.assertThat(spotlessApply.getOutput()).containsPattern("Running npm command.*npm install.* failed with exit code: 1"); + assertThat(spotlessApply.getOutput()).containsPattern("Running npm command.*npm install.* failed with exit code: 1"); } @ParameterizedTest(name = "{index}: verifyCleanAndSpotlessWorks with prettier {0}") @@ -359,9 +360,9 @@ void verifyCleanAndSpotlessWorks(String prettierVersion) throws IOException { "}"); setFile("test.ts").toResource("npm/prettier/config/typescript.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "clean", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); final BuildResult spotlessApply2 = gradleRunner().withArguments("--stacktrace", "clean", "spotlessApply").build(); - Assertions.assertThat(spotlessApply2.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply2.getOutput()).contains("BUILD SUCCESSFUL"); } @ParameterizedTest(name = "{index}: verifyCleanAndSpotlessWithNpmInstallCacheWorks with prettier {0}") @@ -383,9 +384,9 @@ void verifyCleanAndSpotlessWithNpmInstallCacheWorks(String prettierVersion) thro "}"); setFile("test.ts").toResource("npm/prettier/config/typescript.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "clean", "spotlessApply").build(); - Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); final BuildResult spotlessApply2 = gradleRunner().withArguments("--stacktrace", "clean", "spotlessApply").build(); - Assertions.assertThat(spotlessApply2.getOutput()).contains("BUILD SUCCESSFUL"); + assertThat(spotlessApply2.getOutput()).contains("BUILD SUCCESSFUL"); } @ParameterizedTest(name = "{index}: autodetectNpmrcFileConfig with prettier {0}") @@ -412,6 +413,6 @@ void pickupNpmrcFileConfig(String prettierVersion) throws IOException { "}"); setFile("test.ts").toResource("npm/prettier/config/typescript.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").buildAndFail(); - Assertions.assertThat(spotlessApply.getOutput()).containsPattern("Running npm command.*npm install.* failed with exit code: 1"); + assertThat(spotlessApply.getOutput()).containsPattern("Running npm command.*npm install.* failed with exit code: 1"); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/RegisterDependenciesTaskTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/RegisterDependenciesTaskTest.java index 76d0449060..b3ffb6bb04 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/RegisterDependenciesTaskTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/RegisterDependenciesTaskTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,10 @@ */ package com.diffplug.gradle.spotless; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.IOException; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; class RegisterDependenciesTaskTest extends GradleIntegrationHarness { @@ -42,7 +43,7 @@ void duplicateConfigs() throws IOException { setFile("gradle.properties").toLines(); String newestSupported = gradleRunner().withArguments("spotlessCheck").build().getOutput(); - Assertions.assertThat(newestSupported.replace("\r", "")) + assertThat(newestSupported.replace("\r", "")) .startsWith( "> Task :spotlessInternalRegisterDependencies\n") .contains( diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessPluginRedirectTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessPluginRedirectTest.java index ec35e2e446..c7556d0e54 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessPluginRedirectTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessPluginRedirectTest.java @@ -15,9 +15,10 @@ */ package com.diffplug.gradle.spotless; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.IOException; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import com.diffplug.common.base.StringPrinter; @@ -29,7 +30,7 @@ void redirectPluginModernGradle() throws IOException { "plugins {", " id 'com.diffplug.gradle.spotless'", "}"); - Assertions.assertThat(gradleRunner().buildAndFail().getOutput().replace("\r", "")) + assertThat(gradleRunner().buildAndFail().getOutput().replace("\r", "")) .contains(StringPrinter.buildStringFromLines( " > We have moved from 'com.diffplug.gradle.spotless'", " to 'com.diffplug.spotless'", 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 ad2ae7c5aa..2ca42844ea 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,32 +15,36 @@ */ package com.diffplug.gradle.spotless; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import java.io.File; import java.nio.file.Path; -import org.assertj.core.api.Assertions; import org.gradle.api.file.DirectoryProperty; import org.gradle.api.logging.Logger; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import com.diffplug.spotless.Formatter; public class SpotlessTaskImplTest { @Test public void testThrowsMessageContainsFilename() throws Exception { - SpotlessTaskImpl task = Mockito.mock(SpotlessTaskImpl.class, Mockito.CALLS_REAL_METHODS); - Mockito.when(task.getLogger()).thenReturn(Mockito.mock(Logger.class)); + SpotlessTaskImpl task = mock(SpotlessTaskImpl.class, CALLS_REAL_METHODS); + when(task.getLogger()).thenReturn(mock(Logger.class)); File projectDir = Path.of("unitTests", "projectDir").toFile(); - DirectoryProperty projectDirProperty = Mockito.mock(DirectoryProperty.class, Mockito.RETURNS_DEEP_STUBS); - Mockito.when(projectDirProperty.get().getAsFile()).thenReturn(projectDir); + DirectoryProperty projectDirProperty = mock(DirectoryProperty.class, RETURNS_DEEP_STUBS); + when(projectDirProperty.get().getAsFile()).thenReturn(projectDir); - Mockito.when(task.getProjectDir()).thenReturn(projectDirProperty); + when(task.getProjectDir()).thenReturn(projectDirProperty); File input = Path.of("unitTests", "projectDir", "someInput").toFile(); - Formatter formatter = Mockito.mock(Formatter.class); + Formatter formatter = mock(Formatter.class); - Assertions.assertThatThrownBy(() -> task.processInputFile(null, formatter, input, "someInput")).hasMessageContaining(input.toString()); + assertThatThrownBy(() -> task.processInputFile(null, formatter, input, "someInput")).hasMessageContaining(input.toString()); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/TypescriptExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/TypescriptExtensionTest.java index 0882d0f944..5e882e653e 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/TypescriptExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/TypescriptExtensionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -169,8 +169,8 @@ void useEslint() throws IOException { assertFile("test.ts").sameAsResource("npm/eslint/typescript/custom_rules/typescript.clean"); } - @Test @Disabled + @Test void useEslintXoStandardRules() throws IOException { setFile(".eslintrc.js").toResource("npm/eslint/typescript/styleguide/xo/.eslintrc.js"); setFile("tsconfig.json").toResource("npm/eslint/typescript/styleguide/xo/tsconfig.json"); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java index 9b7eccdfff..b5f0d1d3bb 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,10 @@ */ package com.diffplug.gradle.spotless; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.IOException; -import org.assertj.core.api.Assertions; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.TaskOutcome; import org.junit.jupiter.api.Test; @@ -88,8 +89,8 @@ void testPathologicalCase() throws IOException { // the format task is UP-TO-DATE (same inputs), but the apply tasks will run again pauseForFilesystem(); BuildResult buildResult = gradleRunner().withArguments("spotlessApply").build(); - Assertions.assertThat(buildResult.taskPaths(TaskOutcome.UP_TO_DATE)).containsExactly(":spotlessInternalRegisterDependencies", ":spotlessMisc"); - Assertions.assertThat(buildResult.taskPaths(TaskOutcome.SUCCESS)).containsExactly(":spotlessMiscApply", ":spotlessApply"); + assertThat(buildResult.taskPaths(TaskOutcome.UP_TO_DATE)).containsExactly(":spotlessInternalRegisterDependencies", ":spotlessMisc"); + assertThat(buildResult.taskPaths(TaskOutcome.SUCCESS)).containsExactly(":spotlessMiscApply", ":spotlessApply"); assertFile("README.md").hasContent("abc"); // and it'll take two more runs to get to fully UP-TO-DATE 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 cbf3cf0b36..19ca35487f 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 @@ -16,14 +16,15 @@ package com.diffplug.spotless.maven; import static com.diffplug.common.base.Strings.isNullOrEmpty; +import static java.util.Collections.emptyList; import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toSet; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -34,7 +35,6 @@ import java.util.function.Predicate; import java.util.function.Supplier; import java.util.regex.Pattern; -import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; @@ -145,7 +145,7 @@ public abstract class AbstractSpotlessMojo extends AbstractMojo { private LicenseHeader licenseHeader; @Parameter - private List formats = Collections.emptyList(); + private List formats = emptyList(); @Parameter private Css css; @@ -315,7 +315,7 @@ private List collectFiles(FormatterFactory formatterFactory, FormatterConf final String[] includePatterns = this.filePatterns.split(","); final List compiledIncludePatterns = Arrays.stream(includePatterns) .map(Pattern::compile) - .collect(Collectors.toList()); + .collect(toList()); final Predicate shouldInclude = file -> compiledIncludePatterns .stream() .anyMatch(filePattern -> filePattern.matcher(file.getAbsolutePath()) @@ -365,7 +365,7 @@ private Iterable withNormalizedFileSeparators(Iterable patterns) return StreamSupport.stream(patterns.spliterator(), true) .map(pattern -> pattern.replace('/', File.separatorChar)) .map(pattern -> pattern.replace('\\', File.separatorChar)) - .collect(Collectors.toSet()); + .collect(toSet()); } private static String withTrailingSeparator(String path) { diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ArtifactResolver.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ArtifactResolver.java index 10fc03d9b3..14d23dc1b8 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ArtifactResolver.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ArtifactResolver.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.maven; +import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; @@ -22,7 +23,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import java.util.Objects; import java.util.Set; import org.apache.maven.plugin.logging.Log; @@ -50,10 +50,10 @@ public class ArtifactResolver { public ArtifactResolver(RepositorySystem repositorySystem, RepositorySystemSession session, List repositories, Log log) { - this.repositorySystem = Objects.requireNonNull(repositorySystem); - this.session = Objects.requireNonNull(session); - this.repositories = Objects.requireNonNull(repositories); - this.log = Objects.requireNonNull(log); + this.repositorySystem = requireNonNull(repositorySystem); + this.session = requireNonNull(session); + this.repositories = requireNonNull(repositories); + this.log = requireNonNull(log); } /** 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 3781d404be..885a38f39e 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 @@ -17,6 +17,7 @@ import static com.diffplug.common.base.Strings.isNullOrEmpty; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; import java.io.File; import java.net.URISyntaxException; @@ -25,7 +26,6 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; -import java.util.Objects; import org.codehaus.plexus.resource.ResourceManager; import org.codehaus.plexus.resource.loader.FileResourceCreationException; @@ -42,9 +42,9 @@ public class FileLocator { private final File dataDir; public FileLocator(ResourceManager resourceManager, File baseDir, File buildDir) { - this.resourceManager = Objects.requireNonNull(resourceManager); - this.baseDir = Objects.requireNonNull(baseDir); - this.buildDir = Objects.requireNonNull(buildDir); + this.resourceManager = requireNonNull(resourceManager); + this.baseDir = requireNonNull(baseDir); + this.buildDir = requireNonNull(buildDir); this.dataDir = findDataDir(); } 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 6c7cc0d349..d54d80a174 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 @@ -17,6 +17,8 @@ import static com.diffplug.spotless.maven.AbstractSpotlessMojo.RATCHETFROM_NONE; import static java.util.Collections.emptySet; +import static java.util.Objects.requireNonNull; +import static java.util.stream.Collectors.toCollection; import java.io.File; import java.nio.charset.Charset; @@ -26,7 +28,6 @@ import java.util.Optional; import java.util.Set; import java.util.function.Supplier; -import java.util.stream.Collectors; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; @@ -96,7 +97,7 @@ public final Formatter newFormatter(Supplier> filesToFormat, Form List formatterSteps = factories.stream() .filter(Objects::nonNull) // all unrecognized steps from XML config appear as nulls in the list .map(factory -> factory.newFormatterStep(stepConfig)) - .collect(Collectors.toCollection(ArrayList::new)); + .collect(toCollection(ArrayList::new)); if (toggle != null) { List formatterStepsBeforeToggle = formatterSteps; formatterSteps = List.of(toggle.createFence().preserveWithin(formatterStepsBeforeToggle)); @@ -162,7 +163,7 @@ public final void addToggleOffOn(ToggleOffOn toggle) { } protected final void addStepFactory(FormatterStepFactory stepFactory) { - Objects.requireNonNull(stepFactory); + requireNonNull(stepFactory); stepFactories.add(stepFactory); } 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 ab3ec8b958..789ff9474d 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 @@ -15,12 +15,13 @@ */ package com.diffplug.spotless.maven; +import static java.util.stream.Collectors.toList; + import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.HashSet; import java.util.Set; -import java.util.stream.Collectors; import org.eclipse.jgit.lib.IndexDiff; import org.eclipse.jgit.lib.ObjectId; @@ -93,6 +94,6 @@ Iterable getDirtyFiles(File baseDir, String ratchetFrom) throws IOExcept return dirtyPaths.stream() .map(path -> baseDirPath.relativize(Path.of(workTreePath, path)).toString()) - .collect(Collectors.toList()); + .collect(toList()); } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/cpp/Cpp.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/cpp/Cpp.java index 8739a1c717..cbc729deec 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/cpp/Cpp.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/cpp/Cpp.java @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.cpp; -import java.util.Collections; +import static java.util.Collections.emptySet; + import java.util.Set; import org.apache.maven.project.MavenProject; @@ -33,7 +34,7 @@ public class Cpp extends FormatterFactory { @Override public Set defaultIncludes(MavenProject project) { - return Collections.emptySet(); + return emptySet(); } public void addEclipseCdt(EclipseCdt eclipse) { diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/css/Css.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/css/Css.java index 4d465d8939..75bca73a3a 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/css/Css.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/css/Css.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.css; -import java.util.Collections; +import static java.util.Collections.emptySet; + import java.util.Set; import org.apache.maven.project.MavenProject; @@ -28,7 +29,7 @@ public class Css extends FormatterFactory { @Override public Set defaultIncludes(MavenProject project) { - return Collections.emptySet(); + return emptySet(); } @Override diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Format.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Format.java index ccdef479cf..c2feaac619 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Format.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Format.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.generic; -import java.util.Collections; +import static java.util.Collections.emptySet; + import java.util.Set; import org.apache.maven.project.MavenProject; @@ -32,7 +33,7 @@ public class Format extends FormatterFactory { @Override public Set defaultIncludes(MavenProject project) { - return Collections.emptySet(); + return emptySet(); } @Override diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Prettier.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Prettier.java index 7c2894b76a..797109e469 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Prettier.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Prettier.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless.maven.generic; +import static java.util.stream.Collectors.toMap; + import java.io.File; import java.util.AbstractMap; import java.util.Arrays; @@ -22,7 +24,6 @@ import java.util.List; import java.util.Map; import java.util.Properties; -import java.util.stream.Collectors; import org.apache.maven.plugins.annotations.Parameter; @@ -97,7 +98,7 @@ public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) { } return entry; }) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new)); + .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new)); } else { configInline = null; } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/gherkin/Gherkin.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/gherkin/Gherkin.java index 60181d048a..f6bc1ab477 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/gherkin/Gherkin.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/gherkin/Gherkin.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.gherkin; -import java.util.Collections; +import static java.util.Collections.emptySet; + import java.util.Set; import org.apache.maven.project.MavenProject; @@ -28,7 +29,7 @@ public class Gherkin extends FormatterFactory { @Override public Set defaultIncludes(MavenProject project) { - return Collections.emptySet(); + return emptySet(); } @Override diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/go/Go.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/go/Go.java index bb26bd0355..35160c54e4 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/go/Go.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/go/Go.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.go; -import java.util.Collections; +import static java.util.Collections.emptySet; + import java.util.Set; import org.apache.maven.project.MavenProject; @@ -25,7 +26,7 @@ public class Go extends FormatterFactory { @Override public Set defaultIncludes(MavenProject project) { - return Collections.emptySet(); + return emptySet(); } @Override diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/FormatAnnotations.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/FormatAnnotations.java index ac60af0a62..beda8ac139 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/FormatAnnotations.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/FormatAnnotations.java @@ -1,5 +1,5 @@ /* - * Copyright 2022 DiffPlug + * Copyright 2022-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package com.diffplug.spotless.maven.java; -import java.util.Collections; +import static java.util.Collections.emptyList; import com.diffplug.spotless.FormatterStep; import com.diffplug.spotless.java.FormatAnnotationsStep; @@ -27,6 +27,6 @@ public class FormatAnnotations implements FormatterStepFactory { @Override public FormatterStep newFormatterStep(FormatterStepConfig config) { // TODO: Permit customization in Maven build files. - return FormatAnnotationsStep.create(Collections.emptyList(), Collections.emptyList()); + return FormatAnnotationsStep.create(emptyList(), emptyList()); } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/javascript/Javascript.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/javascript/Javascript.java index dc2949ae68..15efba9828 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/javascript/Javascript.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/javascript/Javascript.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.javascript; -import java.util.Collections; +import static java.util.Collections.emptySet; + import java.util.Set; import org.apache.maven.project.MavenProject; @@ -30,7 +31,7 @@ public class Javascript extends FormatterFactory { @Override public Set defaultIncludes(MavenProject project) { - return Collections.emptySet(); + return emptySet(); } @Override diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/JacksonJson.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/JacksonJson.java index ecf925ddbe..f0e18b2fd1 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/JacksonJson.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/JacksonJson.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.json; -import java.util.Collections; +import static java.util.Collections.emptyMap; + import java.util.Map; import org.apache.maven.plugins.annotations.Parameter; @@ -39,10 +40,10 @@ public class JacksonJson implements FormatterStepFactory { private boolean spaceBeforeSeparator = new JacksonJsonConfig().isSpaceBeforeSeparator(); @Parameter - private Map features = Collections.emptyMap(); + private Map features = emptyMap(); @Parameter - private Map jsonFeatures = Collections.emptyMap(); + private Map jsonFeatures = emptyMap(); @Override public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) { diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Json.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Json.java index 80767f41f3..209cf69766 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Json.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Json.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.json; -import java.util.Collections; +import static java.util.Collections.emptySet; + import java.util.Set; import org.apache.maven.project.MavenProject; @@ -30,7 +31,7 @@ public class Json extends FormatterFactory { @Override public Set defaultIncludes(MavenProject project) { - return Collections.emptySet(); + return emptySet(); } @Override diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/kotlin/Ktlint.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/kotlin/Ktlint.java index a54e0d9764..47d15fe9d0 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/kotlin/Ktlint.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/kotlin/Ktlint.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,9 @@ */ package com.diffplug.spotless.maven.kotlin; +import static java.util.Collections.emptyList; + import java.io.File; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -56,7 +57,7 @@ public FormatterStep newFormatterStep(final FormatterStepConfig stepConfig) { editorConfigOverride = new HashMap<>(); } if (customRuleSets == null) { - customRuleSets = Collections.emptyList(); + customRuleSets = emptyList(); } return KtLintStep.create( ktlintVersion, diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/markdown/Markdown.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/markdown/Markdown.java index 0941beb76a..d03fe3d0a5 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/markdown/Markdown.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/markdown/Markdown.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2023 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.markdown; -import java.util.Collections; +import static java.util.Collections.emptySet; + import java.util.Set; import org.apache.maven.project.MavenProject; @@ -32,7 +33,7 @@ public class Markdown extends FormatterFactory { @Override public Set defaultIncludes(MavenProject project) { - return Collections.emptySet(); + return emptySet(); } @Override diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java index 8a9c3990c9..24cd2d23e8 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless.maven.npm; +import static java.util.stream.Collectors.toMap; + import java.io.File; import java.nio.file.Path; import java.util.AbstractMap; @@ -24,7 +26,6 @@ import java.util.Map; import java.util.Objects; import java.util.Properties; -import java.util.stream.Collectors; import org.apache.maven.plugins.annotations.Parameter; @@ -93,6 +94,6 @@ protected Map propertiesAsMap(Properties devDependencyProperties return devDependencyProperties.stringPropertyNames() .stream() .map(name -> new AbstractMap.SimpleEntry<>(name, devDependencyProperties.getProperty(name))) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/python/Python.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/python/Python.java index df7348c16c..7278953226 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/python/Python.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/python/Python.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2023 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.python; -import java.util.Collections; +import static java.util.Collections.emptySet; + import java.util.Set; import org.apache.maven.project.MavenProject; @@ -33,7 +34,7 @@ public class Python extends FormatterFactory { @Override public Set defaultIncludes(MavenProject project) { - return Collections.emptySet(); + return emptySet(); } @Override diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/rdf/Rdf.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/rdf/Rdf.java index d92e09aa58..0a56cd9957 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/rdf/Rdf.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/rdf/Rdf.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.rdf; -import java.util.Collections; +import static java.util.Collections.emptySet; + import java.util.Set; import org.apache.maven.project.MavenProject; @@ -25,7 +26,7 @@ public class Rdf extends FormatterFactory { @Override public Set defaultIncludes(MavenProject project) { - return Collections.emptySet(); + return emptySet(); } @Override diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/sql/Sql.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/sql/Sql.java index 64ebcb55d7..5836369744 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/sql/Sql.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/sql/Sql.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2023 DiffPlug + * Copyright 2020-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.sql; -import java.util.Collections; +import static java.util.Collections.emptySet; + import java.util.Set; import org.apache.maven.project.MavenProject; @@ -30,7 +31,7 @@ public class Sql extends FormatterFactory { @Override public Set defaultIncludes(MavenProject project) { - return Collections.emptySet(); + return emptySet(); } @Override diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/typescript/Typescript.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/typescript/Typescript.java index 2646ca05b0..0d54f4bbb8 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/typescript/Typescript.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/typescript/Typescript.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.typescript; -import java.util.Collections; +import static java.util.Collections.emptySet; + import java.util.Set; import org.apache.maven.project.MavenProject; @@ -30,7 +31,7 @@ public class Typescript extends FormatterFactory { @Override public Set defaultIncludes(MavenProject project) { - return Collections.emptySet(); + return emptySet(); } @Override diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/JacksonYaml.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/JacksonYaml.java index d97cc41647..d019079d3d 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/JacksonYaml.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/JacksonYaml.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.yaml; -import java.util.Collections; +import static java.util.Collections.emptyMap; + import java.util.Map; import org.apache.maven.plugins.annotations.Parameter; @@ -36,10 +37,10 @@ public class JacksonYaml implements FormatterStepFactory { private String version = JacksonYamlStep.defaultVersion(); @Parameter - private Map features = Collections.emptyMap(); + private Map features = emptyMap(); @Parameter - private Map yamlFeatures = Collections.emptyMap(); + private Map yamlFeatures = emptyMap(); @Override public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) { diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/Yaml.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/Yaml.java index e22f6d40ce..1096d5aa02 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/Yaml.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/Yaml.java @@ -1,5 +1,5 @@ /* - * Copyright 2023 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.yaml; -import java.util.Collections; +import static java.util.Collections.emptySet; + import java.util.Set; import org.apache.maven.project.MavenProject; @@ -28,7 +29,7 @@ public class Yaml extends FormatterFactory { @Override public Set defaultIncludes(MavenProject project) { - return Collections.emptySet(); + return emptySet(); } @Override diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/IdeHookTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/IdeHookTest.java index 452efd4a26..04cbe57c0f 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/IdeHookTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/IdeHookTest.java @@ -15,10 +15,11 @@ */ package com.diffplug.spotless.maven; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.File; import java.io.IOException; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -62,28 +63,28 @@ private void runWith(String... arguments) throws IOException, InterruptedExcepti @Test void dirty() throws IOException, InterruptedException { runWith("spotless:apply", "--quiet", "-DspotlessIdeHook=\"" + dirty.getAbsolutePath() + "\"", "-DspotlessIdeHookUseStdOut=true"); - Assertions.assertThat(output).isEqualTo("Mars"); - Assertions.assertThat(error).startsWith("IS DIRTY"); + assertThat(output).isEqualTo("Mars"); + assertThat(error).startsWith("IS DIRTY"); } @Test void clean() throws IOException, InterruptedException { runWith("spotless:apply", "--quiet", "-DspotlessIdeHook=" + clean.getAbsolutePath(), "-DspotlessIdeHookUseStdOut=true"); - Assertions.assertThat(output).isEmpty(); - Assertions.assertThat(error).startsWith("IS CLEAN"); + assertThat(output).isEmpty(); + assertThat(error).startsWith("IS CLEAN"); } @Test void outofbounds() throws IOException, InterruptedException { runWith("spotless:apply", "--quiet", "-DspotlessIdeHook=" + outofbounds.getAbsolutePath(), "-DspotlessIdeHookUseStdOut=true"); - Assertions.assertThat(output).isEmpty(); - Assertions.assertThat(error).isEmpty(); + assertThat(output).isEmpty(); + assertThat(error).isEmpty(); } @Test void notAbsolute() throws IOException, InterruptedException { runWith("spotless:apply", "--quiet", "-DspotlessIdeHook=\"pom.xml\"", "-DspotlessIdeHookUseStdOut=true"); - Assertions.assertThat(output).isEmpty(); - Assertions.assertThat(error).contains("Argument passed to spotlessIdeHook must be an absolute path"); + assertThat(output).isEmpty(); + assertThat(error).contains("Argument passed to spotlessIdeHook must be an absolute path"); } } 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 5e3eb0f46b..365b222c22 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 @@ -16,7 +16,9 @@ package com.diffplug.spotless.maven; import static com.diffplug.common.base.Strings.isNullOrEmpty; +import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.stream; +import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static org.junit.jupiter.api.Assertions.fail; @@ -25,7 +27,6 @@ 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; import java.util.Arrays; @@ -33,7 +34,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.stream.Collectors; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -272,7 +272,7 @@ protected String createPomXmlContent(String[] build, String[] configuration) thr protected String createPomXmlContent(String pomTemplate, Map params) throws IOException { URL url = MavenIntegrationHarness.class.getResource(pomTemplate); - try (BufferedReader reader = Resources.asCharSource(url, StandardCharsets.UTF_8).openBufferedStream()) { + try (BufferedReader reader = Resources.asCharSource(url, UTF_8).openBufferedStream()) { Mustache mustache = mustacheFactory.compile(reader, "pom"); StringWriter writer = new StringWriter(); mustache.execute(writer, params); @@ -361,7 +361,7 @@ protected StringSelfie expectSelfieErrorMsg(ProcessRunner.Result result) { String concatenatedError = result.stdOutUtf8().lines() .map(line -> line.startsWith(ERROR_PREFIX) ? line.substring(ERROR_PREFIX.length()) : null) .filter(Objects::nonNull) - .collect(Collectors.joining("\n")); + .collect(joining("\n")); String sanitizedVersion = concatenatedError.replaceFirst("com\\.diffplug\\.spotless:spotless-maven-plugin:([^:]+):", "com.diffplug.spotless:spotless-maven-plugin:VERSION:"); 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 061f5e6989..1bace7f6c5 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 @@ -15,6 +15,8 @@ */ package com.diffplug.spotless.maven; +import static java.util.Objects.requireNonNull; +import static java.util.stream.Collectors.joining; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; @@ -22,8 +24,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; import java.util.stream.Stream; import com.diffplug.spotless.Jvm; @@ -47,12 +47,12 @@ private MavenRunner() {} private ProcessRunner runner; public MavenRunner withProjectDir(File projectDir) { - this.projectDir = Objects.requireNonNull(projectDir); + this.projectDir = requireNonNull(projectDir); return this; } public MavenRunner withArguments(String... args) { - this.args = Objects.requireNonNull(args); + this.args = requireNonNull(args); return this; } @@ -83,17 +83,17 @@ private Map calculateEnvironment() { // add system properties as environment variables as MAVEN_OPTS or append if already there String sysProps = systemProperties.entrySet().stream() .map(entry -> "-D%s=%s".formatted(entry.getKey(), entry.getValue())) - .collect(Collectors.joining(" ")); + .collect(joining(" ")); String mavenOpts = Stream.of(env.getOrDefault("MAVEN_OPTS", ""), sysProps) - .collect(Collectors.joining(" ")); + .collect(joining(" ")); env.put("MAVEN_OPTS", mavenOpts.trim()); } return env; } private ProcessRunner.Result run() throws IOException, InterruptedException { - Objects.requireNonNull(projectDir, "Need to call withProjectDir() first"); - Objects.requireNonNull(args, "Need to call withArguments() first"); + requireNonNull(projectDir, "Need to call withProjectDir() first"); + 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)); return runner.shellWinUnix(projectDir, calculateEnvironment(), "mvnw " + argsString, "./mvnw " + argsString); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/cpp/ClangMavenIntegrationTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/cpp/ClangMavenIntegrationTest.java index f068cebc45..56052bf792 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/cpp/ClangMavenIntegrationTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/cpp/ClangMavenIntegrationTest.java @@ -23,8 +23,8 @@ @ClangTest class ClangMavenIntegrationTest extends MavenIntegrationHarness { - @Test @ClangTest + @Test void csharp() throws Exception { writePomWithCppSteps("", "", "src/**/*.cs", "", "", "", "", "14.0.0-1ubuntu1.1", "", ""); @@ -33,8 +33,8 @@ void csharp() throws Exception { assertFile("src/test.cs").sameAsResource("clang/example.cs.clean"); } - @Test @ClangTest + @Test void proto() throws Exception { writePomWithCppSteps("", "", "**/*.proto", "", "", "", "", "14.0.0-1ubuntu1.1", "", ""); 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 a0d55da86e..adbf191063 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 @@ -1,5 +1,5 @@ /* - * Copyright 2021-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,13 @@ package com.diffplug.spotless.maven.incremental; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.ByteArrayInputStream; import java.util.Arrays; -import java.util.Collections; import java.util.List; import org.apache.maven.model.Model; @@ -126,7 +126,7 @@ void buildsFingerprintForProjectWithSpotlessPluginInBuildPlugins() { spotlessPlugin.setVersion("1.2.3"); project.getBuild().addPlugin(spotlessPlugin); - PluginFingerprint fingerprint = PluginFingerprint.from(project, Collections.emptyList()); + PluginFingerprint fingerprint = PluginFingerprint.from(project, emptyList()); assertThat(fingerprint).isNotNull(); } @@ -143,7 +143,7 @@ void buildsFingerprintForProjectWithSpotlessPluginInPluginManagement() { pluginManagement.addPlugin(spotlessPlugin); project.getBuild().setPluginManagement(pluginManagement); - PluginFingerprint fingerprint = PluginFingerprint.from(project, Collections.emptyList()); + PluginFingerprint fingerprint = PluginFingerprint.from(project, emptyList()); assertThat(fingerprint).isNotNull(); } 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 5f6bc2750d..8bb62e8c6d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2022-2023 DiffPlug + * Copyright 2022-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.java; -import org.assertj.core.api.Assertions; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; import com.diffplug.spotless.maven.MavenIntegrationHarness; @@ -104,7 +105,7 @@ private void runTest(String dirtyPath, String cleanPath) throws Exception { String path = "src/main/java/test.java"; setFile(path).toResource("java/cleanthat/" + dirtyPath); // .withRemoteDebug(21654) - Assertions.assertThat(mavenRunner().withArguments("spotless:apply").runNoError().stdOutUtf8()).doesNotContain("[ERROR]"); + assertThat(mavenRunner().withArguments("spotless:apply").runNoError().stdOutUtf8()).doesNotContain("[ERROR]"); assertFile(path).sameAsResource("java/cleanthat/" + cleanPath); } } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/LintSuppressionTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/LintSuppressionTest.java index 3f97b63f5d..e1975de5da 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/LintSuppressionTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/LintSuppressionTest.java @@ -161,8 +161,8 @@ private void writePomWithLintSuppressions(String... stepsAndSuppressions) throws } // Create the configuration - String javaGroup = "" + javaSteps.toString() + ""; - String fullConfiguration = javaGroup + globalConfig.toString(); + String javaGroup = "" + javaSteps + ""; + String fullConfiguration = javaGroup + globalConfig; writePom(fullConfiguration); } 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..56318404e5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,8 @@ private static String styleGuideDevDependenciesString(String styleGuideName) { return EslintStyleGuide.fromNameOrNull(styleGuideName).asMavenXmlStringMergedWith(EslintFormatterStep.defaultDevDependencies()); } - @NpmTest @Nested + @NpmTest class EslintCustomRulesTest extends MavenIntegrationHarness { @Test @@ -71,8 +71,8 @@ void eslintConfigJs() throws Exception { } - @NpmTest @Nested + @NpmTest class EslintStyleguidesTest extends MavenIntegrationHarness { @ParameterizedTest(name = "{index}: eslint js formatting with configFile using styleguide {0}") 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 b46a45a442..79ac68dcbb 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 @@ -15,7 +15,8 @@ */ package com.diffplug.spotless.maven.kotlin; -import org.assertj.core.api.Assertions; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; import com.diffplug.spotless.ProcessRunner; @@ -92,7 +93,7 @@ void testWithCustomRuleSetApply() throws Exception { """); setFile("src/main/kotlin/Main.kt").toResource("kotlin/ktlint/listScreen.dirty"); ProcessRunner.Result result = mavenRunner().withArguments("spotless:check").runHasError(); - Assertions.assertThat(result.toString()).contains("Composable functions that return Unit should start with an uppercase letter."); + assertThat(result.toString()).contains("Composable functions that return Unit should start with an uppercase letter."); } private void checkKtlintOfficialStyle() throws Exception { 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 75d4b3f693..4059441476 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 @@ -16,6 +16,7 @@ package com.diffplug.spotless.maven.npm; import static com.diffplug.spotless.maven.npm.AbstractNpmFormatterStepFactory.SPOTLESS_NPM_INSTALL_CACHE_DEFAULT_NAME; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; @@ -25,7 +26,6 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -48,7 +48,7 @@ void prettierTypescriptWithoutCache() throws Exception { " .prettierrc.yml", ""); Result result = run("typescript", suffix); - Assertions.assertThat(result.stdOutUtf8()).doesNotContain("Caching node_modules for").doesNotContain("Using cached node_modules for"); + assertThat(result.stdOutUtf8()).doesNotContain("Caching node_modules for").doesNotContain("Using cached node_modules for"); } @Test @@ -61,7 +61,7 @@ void prettierTypescriptWithDefaultCache() throws Exception { " true", ""); Result result = run("typescript", suffix); - Assertions.assertThat(result.stdOutUtf8()) + assertThat(result.stdOutUtf8()) .contains("Caching node_modules for") .contains(SPOTLESS_NPM_INSTALL_CACHE_DEFAULT_NAME) .doesNotContain("Using cached node_modules for"); @@ -78,7 +78,7 @@ void prettierTypescriptWithDefaultCacheIsReusedOnSecondRun() throws Exception { " true", ""); Result result1 = run("typescript", suffix); - Assertions.assertThat(result1.stdOutUtf8()) + assertThat(result1.stdOutUtf8()) .contains("Caching node_modules for") .contains(SPOTLESS_NPM_INSTALL_CACHE_DEFAULT_NAME) .doesNotContain("Using cached node_modules for"); @@ -87,7 +87,7 @@ void prettierTypescriptWithDefaultCacheIsReusedOnSecondRun() throws Exception { recursiveDelete(Path.of(rootFolder().getAbsolutePath(), "target"), SPOTLESS_NPM_INSTALL_CACHE_DEFAULT_NAME); Result result2 = run("typescript", suffix); - Assertions.assertThat(result2.stdOutUtf8()) + assertThat(result2.stdOutUtf8()) .doesNotContain("Caching node_modules for") .contains(SPOTLESS_NPM_INSTALL_CACHE_DEFAULT_NAME) .contains("Using cached node_modules for"); @@ -104,7 +104,7 @@ void prettierTypescriptWithSpecificCache() throws Exception { " " + cacheDir.getAbsolutePath() + "", ""); Result result = run("typescript", suffix); - Assertions.assertThat(result.stdOutUtf8()) + assertThat(result.stdOutUtf8()) .contains("Caching node_modules for") .contains(Path.of(cacheDir.getAbsolutePath()).toAbsolutePath().toString()) .doesNotContain("Using cached node_modules for"); @@ -122,7 +122,7 @@ void prettierTypescriptWithSpecificCacheIsUsedOnSecondRun() throws Exception { " " + cacheDir.getAbsolutePath() + "", ""); Result result1 = run("typescript", suffix); - Assertions.assertThat(result1.stdOutUtf8()) + assertThat(result1.stdOutUtf8()) .contains("Caching node_modules for") .contains(Path.of(cacheDir.getAbsolutePath()).toAbsolutePath().toString()) .doesNotContain("Using cached node_modules for"); @@ -131,7 +131,7 @@ void prettierTypescriptWithSpecificCacheIsUsedOnSecondRun() throws Exception { recursiveDelete(Path.of(rootFolder().getAbsolutePath(), "target"), null); Result result2 = run("typescript", suffix); - Assertions.assertThat(result2.stdOutUtf8()) + assertThat(result2.stdOutUtf8()) .doesNotContain("Caching node_modules for") .contains(Path.of(cacheDir.getAbsolutePath()).toAbsolutePath().toString()) .contains("Using cached node_modules for"); 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 afda22e06b..69974b19da 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -210,8 +210,8 @@ void eslintStyleguideStandardWithTypescript() throws Exception { assertFile(TEST_FILE_PATH).sameAsResource("npm/eslint/typescript/styleguide/standard_with_typescript/typescript.clean"); } - @Test @Disabled + @Test void eslintStyleguideXo() throws Exception { writePomWithTypescriptSteps( TEST_FILE_PATH, diff --git a/rewrite.yml b/rewrite.yml index a7f4e4654d..b27ea2ad97 100644 --- a/rewrite.yml +++ b/rewrite.yml @@ -10,7 +10,6 @@ tags: - cleanup recipeList: - org.openrewrite.gradle.EnableGradleBuildCache - - org.openrewrite.gradle.EnableGradleParallelExecution - org.openrewrite.gradle.GradleBestPractices - org.openrewrite.java.RemoveUnusedImports - org.openrewrite.java.format.NormalizeFormat diff --git a/settings.gradle b/settings.gradle index 03e841f0ae..5b63b1a24d 100644 --- a/settings.gradle +++ b/settings.gradle @@ -23,6 +23,7 @@ plugins { id 'com.gradle.develocity' version '4.2.1' // https://github.com/equodev/equo-ide/blob/main/plugin-gradle/CHANGELOG.md id 'dev.equo.ide' version '1.7.8' apply false + id 'net.ltgt.errorprone' version '4.3.0' apply false id 'org.openrewrite.rewrite' version '7.17.0' apply false } diff --git a/testlib/src/main/java/com/diffplug/spotless/ClearGitConfig.java b/testlib/src/main/java/com/diffplug/spotless/ClearGitConfig.java index 1655845831..57e28c4aa0 100644 --- a/testlib/src/main/java/com/diffplug/spotless/ClearGitConfig.java +++ b/testlib/src/main/java/com/diffplug/spotless/ClearGitConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,10 +30,10 @@ import org.junit.jupiter.api.parallel.ResourceAccessMode; import org.junit.jupiter.api.parallel.ResourceLock; -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) @ExtendWith(ClearGitConfig.GitConfigExtension.class) @ResourceLock(value = "GIT", mode = ResourceAccessMode.READ_WRITE) +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) public @interface ClearGitConfig { class GitConfigExtension implements BeforeEachCallback, AfterEachCallback { diff --git a/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java b/testlib/src/main/java/com/diffplug/spotless/ReflectionUtil.java index 4d0a340f42..1590b08311 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-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ public static void dumpAllInfo(String name, Object obj) { public static void dumpMethod(Method method) { System.out.print(Modifier.toString(method.getModifiers())); - System.out.print(" " + method.getReturnType().toString()); + System.out.print(" " + method.getReturnType()); System.out.print(" " + method.getName() + "("); Iterator paramIter = Arrays.asList(method.getParameters()).iterator(); while (paramIter.hasNext()) { diff --git a/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java b/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java index db522db947..8ba48ad593 100644 --- a/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java +++ b/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import java.io.BufferedReader; @@ -24,7 +25,6 @@ import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -92,7 +92,7 @@ public List listTestResources(String path) throws IOException { throw new RuntimeException("Resource not found in classpath: '%s' - did you mean '/%1$s'?".formatted(path)); } } - try (BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) { + try (BufferedReader br = new BufferedReader(new InputStreamReader(in, UTF_8))) { String resource; while ((resource = br.readLine()) != null) { filenames.add(resource); @@ -107,7 +107,7 @@ public String relativeToRoot(String path) { } public String read(String path) throws IOException { - return read(newFile(path).toPath(), StandardCharsets.UTF_8); + return read(newFile(path).toPath(), UTF_8); } public String read(Path path, Charset encoding) throws IOException { @@ -127,7 +127,7 @@ public void replace(String path, String toReplace, String replaceWith) throws IO public static String getTestResource(String filename) { Optional resourceUrl = getTestResourceUrl(filename); if (resourceUrl.isPresent()) { - return ThrowingEx.get(() -> LineEnding.toUnix(Resources.toString(resourceUrl.orElseThrow(), StandardCharsets.UTF_8))); + return ThrowingEx.get(() -> LineEnding.toUnix(Resources.toString(resourceUrl.orElseThrow(), UTF_8))); } throw new IllegalArgumentException("No such resource " + filename); } @@ -164,7 +164,7 @@ public File createTestFile(String filename, UnaryOperator fileContentsPr String name = lastSlash >= 0 ? filename.substring(lastSlash) : filename; File file = newFile(name); file.getParentFile().mkdirs(); - ThrowingEx.run(() -> Files.write(file.toPath(), fileContentsProcessor.apply(getTestResource(filename)).getBytes(StandardCharsets.UTF_8))); + ThrowingEx.run(() -> Files.write(file.toPath(), fileContentsProcessor.apply(getTestResource(filename)).getBytes(UTF_8))); return file; } @@ -186,11 +186,11 @@ private ReadAsserter(File file) { } public void hasContent(String expected) { - hasContent(expected, StandardCharsets.UTF_8); + hasContent(expected, UTF_8); } public void hasDifferentContent(String expected) { - hasDifferentContent(expected, StandardCharsets.UTF_8); + hasDifferentContent(expected, UTF_8); } public void hasContent(String expected, Charset charset) { @@ -236,7 +236,7 @@ public File toLines(String... lines) { } public File toContent(String content) { - return toContent(content, StandardCharsets.UTF_8); + return toContent(content, UTF_8); } public File toContent(String content, Charset charset) { @@ -245,7 +245,7 @@ public File toContent(String content, Charset charset) { } public File toResource(String path) { - ThrowingEx.run(() -> Files.write(file.toPath(), getTestResource(path).getBytes(StandardCharsets.UTF_8))); + ThrowingEx.run(() -> Files.write(file.toPath(), getTestResource(path).getBytes(UTF_8))); return file; } diff --git a/testlib/src/main/java/com/diffplug/spotless/StepHarness.java b/testlib/src/main/java/com/diffplug/spotless/StepHarness.java index feb451d1fb..e8d2f6a8bf 100644 --- a/testlib/src/main/java/com/diffplug/spotless/StepHarness.java +++ b/testlib/src/main/java/com/diffplug/spotless/StepHarness.java @@ -15,10 +15,10 @@ */ package com.diffplug.spotless; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; -import java.nio.charset.StandardCharsets; import java.util.Arrays; import com.diffplug.selfie.Selfie; @@ -40,7 +40,7 @@ public static StepHarness forSteps(FormatterStep... steps) { return forFormatter(Formatter.builder() .steps(Arrays.asList(steps)) .lineEndingsPolicy(LineEnding.UNIX.createPolicy()) - .encoding(StandardCharsets.UTF_8) + .encoding(UTF_8) .build()); } @@ -53,7 +53,7 @@ public static StepHarness forStepNoRoundtrip(FormatterStep step) { return new StepHarness(Formatter.builder() .steps(Arrays.asList(step)) .lineEndingsPolicy(LineEnding.UNIX.createPolicy()) - .encoding(StandardCharsets.UTF_8) + .encoding(UTF_8) .build(), RoundTrip.DONT_ROUNDTRIP); } diff --git a/testlib/src/main/java/com/diffplug/spotless/StepHarnessBase.java b/testlib/src/main/java/com/diffplug/spotless/StepHarnessBase.java index d86021ef99..5e1891b558 100644 --- a/testlib/src/main/java/com/diffplug/spotless/StepHarnessBase.java +++ b/testlib/src/main/java/com/diffplug/spotless/StepHarnessBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,8 @@ */ package com.diffplug.spotless; -import java.util.Objects; - -import org.assertj.core.api.Assertions; +import static java.util.Objects.requireNonNull; +import static org.assertj.core.api.Assertions.assertThat; class StepHarnessBase implements AutoCloseable { enum RoundTrip { @@ -28,12 +27,12 @@ enum RoundTrip { protected StepHarnessBase(Formatter formatter, RoundTrip roundTrip) { if (roundTrip == RoundTrip.DONT_ROUNDTRIP) { - this.formatter = Objects.requireNonNull(formatter); + this.formatter = requireNonNull(formatter); return; } Formatter roundTripped = SerializableEqualityTester.reserialize(formatter); if (roundTrip == RoundTrip.ASSERT_EQUAL) { - Assertions.assertThat(roundTripped).isEqualTo(formatter); + assertThat(roundTripped).isEqualTo(formatter); } this.formatter = roundTripped; } diff --git a/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java b/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java index 9f1658b9d1..532ecd0642 100644 --- a/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java +++ b/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java @@ -15,13 +15,13 @@ */ package com.diffplug.spotless; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Collections.singletonList; +import static java.util.Objects.requireNonNull; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.Objects; import com.diffplug.selfie.StringSelfie; @@ -31,15 +31,15 @@ public final class StepHarnessWithFile extends StepHarnessBase { private StepHarnessWithFile(ResourceHarness harness, Formatter formatter, RoundTrip roundTrip) { super(formatter, roundTrip); - this.harness = Objects.requireNonNull(harness); + this.harness = requireNonNull(harness); } /** Creates a harness for testing steps which do depend on the file. */ public static StepHarnessWithFile forStep(ResourceHarness harness, FormatterStep step) { return forFormatter(harness, Formatter.builder() - .encoding(StandardCharsets.UTF_8) + .encoding(UTF_8) .lineEndingsPolicy(LineEnding.UNIX.createPolicy()) - .steps(Collections.singletonList(step)) + .steps(singletonList(step)) .build()); } diff --git a/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java b/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java index 672dd8eba9..69ee3a80ec 100644 --- a/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java +++ b/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java @@ -15,12 +15,13 @@ */ package com.diffplug.spotless; +import static java.util.Comparator.reverseOrder; + import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.file.Path; -import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; @@ -86,7 +87,7 @@ private static Provisioner createWithRepositories(Consumer re // delete the temp dir try { java.nio.file.Files.walk(tempDir.toPath()) - .sorted(Comparator.reverseOrder()) + .sorted(reverseOrder()) .map(Path::toFile) .forEach(File::delete); } catch (IOException e) { diff --git a/testlib/src/main/java/com/diffplug/spotless/npm/EslintStyleGuide.java b/testlib/src/main/java/com/diffplug/spotless/npm/EslintStyleGuide.java index 4e1d168a2a..4cc271a8b6 100644 --- a/testlib/src/main/java/com/diffplug/spotless/npm/EslintStyleGuide.java +++ b/testlib/src/main/java/com/diffplug/spotless/npm/EslintStyleGuide.java @@ -15,9 +15,10 @@ */ package com.diffplug.spotless.npm; +import static java.util.stream.Collectors.joining; + import java.util.LinkedHashMap; import java.util.Map; -import java.util.stream.Collectors; import javax.annotation.Nonnull; @@ -26,8 +27,8 @@ */ public enum EslintStyleGuide { TS_STANDARD_WITH_TYPESCRIPT("standard-with-typescript") { - @Override - public @Nonnull Map devDependencies() { + @Nonnull + public @Override Map devDependencies() { Map dependencies = new LinkedHashMap<>(); dependencies.put("@typescript-eslint/eslint-plugin", "^5.62.0"); dependencies.put("@typescript-eslint/parser", "^5.62.0"); @@ -39,8 +40,8 @@ public enum EslintStyleGuide { } }, TS_XO_TYPESCRIPT("xo-typescript") { - @Override - public @Nonnull Map devDependencies() { + @Nonnull + public @Override Map devDependencies() { Map dependencies = new LinkedHashMap<>(); dependencies.put("eslint-config-xo", "^0.43.1"); dependencies.put("eslint-config-xo-typescript", "^1.0.0"); @@ -48,8 +49,8 @@ public enum EslintStyleGuide { } }, JS_AIRBNB("airbnb") { - @Override - public @Nonnull Map devDependencies() { + @Nonnull + public @Override Map devDependencies() { Map dependencies = new LinkedHashMap<>(); dependencies.put("eslint-config-airbnb-base", "^15.0.0"); dependencies.put("eslint-plugin-import", "^2.27.5"); @@ -57,16 +58,16 @@ public enum EslintStyleGuide { } }, JS_GOOGLE("google") { - @Override - public @Nonnull Map devDependencies() { + @Nonnull + public @Override Map devDependencies() { Map dependencies = new LinkedHashMap<>(); dependencies.put("eslint-config-google", "^0.14.0"); return dependencies; } }, JS_STANDARD("standard") { - @Override - public @Nonnull Map devDependencies() { + @Nonnull + public @Override Map devDependencies() { Map dependencies = new LinkedHashMap<>(); dependencies.put("eslint-config-standard", "^17.1.0"); dependencies.put("eslint-plugin-import", "^2.27.5"); @@ -76,8 +77,8 @@ public enum EslintStyleGuide { } }, JS_XO("xo") { - @Override - public @Nonnull Map devDependencies() { + @Nonnull + public @Override Map devDependencies() { Map dependencies = new LinkedHashMap<>(); dependencies.put("eslint-config-xo", "^0.43.1"); return dependencies; @@ -110,13 +111,13 @@ public Map mergedWith(Map devDependencies) { public String asGradleMapStringMergedWith(Map devDependencies) { return mergedWith(devDependencies).entrySet().stream() .map(entry -> "'" + entry.getKey() + "': '" + entry.getValue() + "'") - .collect(Collectors.joining(", ", "[", "]")); + .collect(joining(", ", "[", "]")); } public String asMavenXmlStringMergedWith(Map devDependencies) { return mergedWith(devDependencies).entrySet().stream() .map(entry -> "%s%s".formatted(entry.getKey(), entry.getValue())) - .collect(Collectors.joining("", "", "")); + .collect(joining("", "", "")); } } diff --git a/testlib/src/main/java/com/diffplug/spotless/tag/BlackTest.java b/testlib/src/main/java/com/diffplug/spotless/tag/BlackTest.java index d0b34be10b..9d1a8063ab 100644 --- a/testlib/src/main/java/com/diffplug/spotless/tag/BlackTest.java +++ b/testlib/src/main/java/com/diffplug/spotless/tag/BlackTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import org.junit.jupiter.api.Tag; -@Target({TYPE, METHOD}) @Retention(RUNTIME) @Tag("black") +@Target({METHOD, TYPE}) public @interface BlackTest {} diff --git a/testlib/src/main/java/com/diffplug/spotless/tag/BufTest.java b/testlib/src/main/java/com/diffplug/spotless/tag/BufTest.java index 19923f4c6d..7ae8d36c59 100644 --- a/testlib/src/main/java/com/diffplug/spotless/tag/BufTest.java +++ b/testlib/src/main/java/com/diffplug/spotless/tag/BufTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2022-2024 DiffPlug + * Copyright 2022-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import org.junit.jupiter.api.Tag; -@Target({TYPE, METHOD}) @Retention(RUNTIME) @Tag("buf") +@Target({METHOD, TYPE}) public @interface BufTest {} diff --git a/testlib/src/main/java/com/diffplug/spotless/tag/ClangTest.java b/testlib/src/main/java/com/diffplug/spotless/tag/ClangTest.java index e9f893bdfe..7b1ced43bb 100644 --- a/testlib/src/main/java/com/diffplug/spotless/tag/ClangTest.java +++ b/testlib/src/main/java/com/diffplug/spotless/tag/ClangTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import org.junit.jupiter.api.Tag; -@Target({TYPE, METHOD}) @Retention(RUNTIME) @Tag("clang") +@Target({METHOD, TYPE}) public @interface ClangTest {} diff --git a/testlib/src/main/java/com/diffplug/spotless/tag/GofmtTest.java b/testlib/src/main/java/com/diffplug/spotless/tag/GofmtTest.java index 6228a84895..4ca99cf25c 100644 --- a/testlib/src/main/java/com/diffplug/spotless/tag/GofmtTest.java +++ b/testlib/src/main/java/com/diffplug/spotless/tag/GofmtTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import org.junit.jupiter.api.Tag; -@Target({TYPE, METHOD}) @Retention(RUNTIME) @Tag("gofmt") +@Target({METHOD, TYPE}) public @interface GofmtTest {} diff --git a/testlib/src/main/java/com/diffplug/spotless/tag/IdeaTest.java b/testlib/src/main/java/com/diffplug/spotless/tag/IdeaTest.java index c9f351cdcb..c4d4983387 100644 --- a/testlib/src/main/java/com/diffplug/spotless/tag/IdeaTest.java +++ b/testlib/src/main/java/com/diffplug/spotless/tag/IdeaTest.java @@ -24,7 +24,7 @@ import org.junit.jupiter.api.Tag; -@Target({TYPE, METHOD}) @Retention(RUNTIME) @Tag("idea") +@Target({METHOD, TYPE}) public @interface IdeaTest {} diff --git a/testlib/src/main/java/com/diffplug/spotless/tag/NpmTest.java b/testlib/src/main/java/com/diffplug/spotless/tag/NpmTest.java index 4f19ce3dfe..3cf09f249b 100644 --- a/testlib/src/main/java/com/diffplug/spotless/tag/NpmTest.java +++ b/testlib/src/main/java/com/diffplug/spotless/tag/NpmTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import org.junit.jupiter.api.Tag; -@Target({TYPE, METHOD}) @Retention(RUNTIME) @Tag("npm") +@Target({METHOD, TYPE}) public @interface NpmTest {} diff --git a/testlib/src/main/java/com/diffplug/spotless/tag/ShfmtTest.java b/testlib/src/main/java/com/diffplug/spotless/tag/ShfmtTest.java index e7998f6a83..8f3eb9a159 100644 --- a/testlib/src/main/java/com/diffplug/spotless/tag/ShfmtTest.java +++ b/testlib/src/main/java/com/diffplug/spotless/tag/ShfmtTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 DiffPlug + * Copyright 2024-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import org.junit.jupiter.api.Tag; -@Target({TYPE, METHOD}) @Retention(RUNTIME) @Tag("shfmt") +@Target({METHOD, TYPE}) public @interface ShfmtTest {} diff --git a/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java b/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java index 953dbb8884..ad29043c80 100644 --- a/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/EncodingErrorMsgTest.java @@ -15,13 +15,14 @@ */ package com.diffplug.spotless; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; import javax.annotation.Nullable; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; class EncodingErrorMsgTest { @@ -49,9 +50,9 @@ 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); - String actualMessage = EncodingErrorMsg.msg(asUTF, cp1252, StandardCharsets.UTF_8); - Assertions.assertThat(actualMessage).isEqualTo(expectedMessage); + String asUTF = new String(cp1252, UTF_8); + String actualMessage = EncodingErrorMsg.msg(asUTF, cp1252, UTF_8); + assertThat(actualMessage).isEqualTo(expectedMessage); } @Test @@ -86,17 +87,17 @@ void utf8asCP1252() throws UnsupportedEncodingException { } private void utf8asCP1252(String test, @Nullable String expectedMessage) throws UnsupportedEncodingException { - byte[] utf8 = test.getBytes(StandardCharsets.UTF_8); + byte[] utf8 = test.getBytes(UTF_8); String asCp1252 = new String(utf8, "cp1252"); String actualMessage = EncodingErrorMsg.msg(asCp1252, utf8, Charset.forName("cp1252")); - Assertions.assertThat(actualMessage).isEqualTo(expectedMessage); + assertThat(actualMessage).isEqualTo(expectedMessage); } @Test void canUseUnrepresentableOnPurpose() throws UnsupportedEncodingException { String pathologic = new String(new char[]{EncodingErrorMsg.UNREPRESENTABLE}); - byte[] pathologicBytes = pathologic.getBytes(StandardCharsets.UTF_8); - String pathologicMsg = EncodingErrorMsg.msg(pathologic, pathologicBytes, StandardCharsets.UTF_8); - Assertions.assertThat(pathologicMsg).isNull(); + byte[] pathologicBytes = pathologic.getBytes(UTF_8); + String pathologicMsg = EncodingErrorMsg.msg(pathologic, pathologicBytes, UTF_8); + 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 88e4175046..8ba6e99d8d 100644 --- a/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless; +import static java.util.Collections.shuffle; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.condition.OS.WINDOWS; @@ -23,10 +24,8 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.List; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledOnOs; @@ -65,7 +64,7 @@ void testFromFilesAndDirectory() throws IOException { File dir = new File(rootFolder(), "dir"); List files = getTestFiles(inputPaths); files.add(dir); - Collections.shuffle(files); + shuffle(files); assertThatThrownBy(() -> FileSignature.signAsList(files)) .isInstanceOf(IllegalArgumentException.class); } @@ -83,10 +82,10 @@ void testSubpath() { assertThat(FileSignature.subpath("root/", "root/child")).isEqualTo("child"); } - @Test @EnabledOnOs(WINDOWS) + @Test void windowsRoot() { String subpath = FileSignature.subpath("S://", "S:/build.gradle"); - Assertions.assertThat(subpath).isEqualTo("build.gradle"); + assertThat(subpath).isEqualTo("build.gradle"); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java b/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java index 7c7afb9bf2..47dd2eeae3 100644 --- a/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/FormatterPropertiesTest.java @@ -15,7 +15,9 @@ */ package com.diffplug.spotless; +import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; @@ -25,10 +27,8 @@ import java.util.LinkedList; import java.util.List; import java.util.Properties; -import java.util.stream.Collectors; import org.assertj.core.api.AbstractAssert; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; class FormatterPropertiesTest extends ResourceHarness { @@ -50,15 +50,15 @@ class FormatterPropertiesTest extends ResourceHarness { }; private List validPropertiesResources() { - return List.of(VALID_SETTINGS_RESOURCES).stream().filter(it -> !it.endsWith(".xml")).collect(Collectors.toList()); + return List.of(VALID_SETTINGS_RESOURCES).stream().filter(it -> !it.endsWith(".xml")).collect(toList()); } private List validXmlResources() { - return List.of(VALID_SETTINGS_RESOURCES).stream().filter(it -> it.endsWith(".xml")).collect(Collectors.toList()); + return List.of(VALID_SETTINGS_RESOURCES).stream().filter(it -> it.endsWith(".xml")).collect(toList()); } private List invalidXmlResources() { - return List.of(INVALID_SETTINGS_RESOURCES).stream().filter(it -> it.endsWith(".xml")).collect(Collectors.toList()); + return List.of(INVALID_SETTINGS_RESOURCES).stream().filter(it -> it.endsWith(".xml")).collect(toList()); } private static final String[] VALID_VALUES = { @@ -181,7 +181,7 @@ void nonExistingFile() throws IOException { String filePath = FileSignature.pathUnixToNative("does/not/exist.properties"); try { FormatterProperties.from(new File(filePath)); - Assertions.fail("Should have thrown"); + fail("Should have thrown"); } catch (IllegalArgumentException ex) { assertThat(ex.getMessage()) .as("IllegalArgumentException does not contain path of non-existing file.").contains(filePath); diff --git a/testlib/src/test/java/com/diffplug/spotless/FormatterTest.java b/testlib/src/test/java/com/diffplug/spotless/FormatterTest.java index cbd219b33d..b7b70175ac 100644 --- a/testlib/src/test/java/com/diffplug/spotless/FormatterTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/FormatterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,12 +15,14 @@ */ package com.diffplug.spotless; +import static java.nio.charset.StandardCharsets.UTF_16; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.diffplug.spotless.generic.EndWithNewlineStep; @@ -28,9 +30,9 @@ class FormatterTest { @Test void toUnix() { - Assertions.assertEquals("1\n2\n3", LineEnding.toUnix("1\n2\n3")); - Assertions.assertEquals("1\n2\n3", LineEnding.toUnix("1\r2\r3")); - Assertions.assertEquals("1\n2\n3", LineEnding.toUnix("1\r\n2\r\n3")); + assertEquals("1\n2\n3", LineEnding.toUnix("1\n2\n3")); + assertEquals("1\n2\n3", LineEnding.toUnix("1\r2\r3")); + assertEquals("1\n2\n3", LineEnding.toUnix("1\r\n2\r\n3")); } // Formatter normally needs to be closed, but no resources will be leaked in this special case @@ -38,7 +40,7 @@ void toUnix() { void equality() { new SerializableEqualityTester() { private LineEnding.Policy lineEndingsPolicy = LineEnding.UNIX.createPolicy(); - private Charset encoding = StandardCharsets.UTF_8; + private Charset encoding = UTF_8; private List steps = new ArrayList<>(); @Override @@ -48,7 +50,7 @@ protected void setupTest(API api) throws Exception { lineEndingsPolicy = LineEnding.WINDOWS.createPolicy(); api.areDifferentThan(); - encoding = StandardCharsets.UTF_16; + encoding = UTF_16; api.areDifferentThan(); steps.add(EndWithNewlineStep.create()); diff --git a/testlib/src/test/java/com/diffplug/spotless/JvmTest.java b/testlib/src/test/java/com/diffplug/spotless/JvmTest.java index 746ea5d46a..3979509e8d 100644 --- a/testlib/src/test/java/com/diffplug/spotless/JvmTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/JvmTest.java @@ -48,8 +48,8 @@ void supportAdd() { assertThat(testSupport.toString()).contains("%s alternatives".formatted(TEST_NAME)); } - @ParameterizedTest(name = "{index} {1}") @MethodSource + @ParameterizedTest(name = "{index} {1}") void supportAddFailsFor(Consumer> configuration, String nameNotUsed) { assertThrows(IllegalArgumentException.class, () -> configuration.accept(testSupport)); } diff --git a/testlib/src/test/java/com/diffplug/spotless/PaddedCellTest.java b/testlib/src/test/java/com/diffplug/spotless/PaddedCellTest.java index 2820aadeef..3d06e44d89 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-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,10 +18,12 @@ import static com.diffplug.spotless.PaddedCell.Type.CONVERGE; import static com.diffplug.spotless.PaddedCell.Type.CYCLE; import static com.diffplug.spotless.PaddedCell.Type.DIVERGE; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; @@ -29,7 +31,6 @@ import java.util.List; import java.util.function.BiConsumer; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -50,23 +51,23 @@ private void testCase(SerializedFunction step, String input, Pad formatterSteps.add(NeverUpToDateStep.create("step", step)); try (Formatter formatter = Formatter.builder() .lineEndingsPolicy(LineEnding.UNIX.createPolicy()) - .encoding(StandardCharsets.UTF_8) + .encoding(UTF_8) .steps(formatterSteps).build()) { File file = new File(rootFolder, "input"); - Files.write(file.toPath(), input.getBytes(StandardCharsets.UTF_8)); + Files.write(file.toPath(), input.getBytes(UTF_8)); PaddedCell result = PaddedCell.check(formatter, file); - Assertions.assertEquals(misbehaved, result.misbehaved()); - Assertions.assertEquals(expectedOutputType, result.type()); + assertEquals(misbehaved, result.misbehaved()); + assertEquals(expectedOutputType, result.type()); String actual = String.join(",", result.steps()); - Assertions.assertEquals(expectedSteps, actual); + assertEquals(expectedSteps, actual); if (canonical == null) { - Assertions.assertThrows(IllegalArgumentException.class, result::canonical); + assertThrows(IllegalArgumentException.class, result::canonical); } else { - Assertions.assertEquals(canonical, result.canonical()); + assertEquals(canonical, result.canonical()); } } } @@ -121,7 +122,7 @@ void cycleOrder() { Collections.rotate(unordered, 1); PaddedCell result = CYCLE.create(rootFolder, unordered); // make sure the canonical result is always the appropriate one - Assertions.assertEquals(canonical, result.canonical()); + assertEquals(canonical, result.canonical()); } }; // alphabetic diff --git a/testlib/src/test/java/com/diffplug/spotless/ProvisionerTest.java b/testlib/src/test/java/com/diffplug/spotless/ProvisionerTest.java index e3616a5844..10743d6fc6 100644 --- a/testlib/src/test/java/com/diffplug/spotless/ProvisionerTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/ProvisionerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,22 +15,23 @@ */ package com.diffplug.spotless; +import static java.util.stream.Collectors.toSet; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.File; import java.util.Arrays; -import java.util.stream.Collectors; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; class ProvisionerTest { @Test void testManipulation() { - Provisioner provisioner = (withTransitives, deps) -> deps.stream().map(File::new).collect(Collectors.toSet()); - Assertions.assertThat(provisioner.provisionWithTransitives(true, "a")) + Provisioner provisioner = (withTransitives, deps) -> deps.stream().map(File::new).collect(toSet()); + assertThat(provisioner.provisionWithTransitives(true, "a")) .containsExactlyInAnyOrder(new File("a")); - Assertions.assertThat(provisioner.provisionWithTransitives(true, "a", "a")) + assertThat(provisioner.provisionWithTransitives(true, "a", "a")) .containsExactlyInAnyOrder(new File("a")); - Assertions.assertThat(provisioner.provisionWithTransitives(true, Arrays.asList("a", "a"))) + assertThat(provisioner.provisionWithTransitives(true, Arrays.asList("a", "a"))) .containsExactlyInAnyOrder(new File("a")); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/generic/FenceStepTest.java b/testlib/src/test/java/com/diffplug/spotless/generic/FenceStepTest.java index 0081b39b42..77af0c3a84 100644 --- a/testlib/src/test/java/com/diffplug/spotless/generic/FenceStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/generic/FenceStepTest.java @@ -132,8 +132,8 @@ public String getName() { return uppercase ? "uppercase" : "lowercase"; } - @org.jetbrains.annotations.Nullable @Override - public String format(String rawUnix, File file) throws Exception { + @Override + @org.jetbrains.annotations.Nullable public String format(String rawUnix, File file) throws Exception { return uppercase ? rawUnix.toUpperCase() : rawUnix.toLowerCase(); } diff --git a/testlib/src/test/java/com/diffplug/spotless/generic/IdeaStepTest.java b/testlib/src/test/java/com/diffplug/spotless/generic/IdeaStepTest.java index d7dbc8025a..cafed62033 100644 --- a/testlib/src/test/java/com/diffplug/spotless/generic/IdeaStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/generic/IdeaStepTest.java @@ -15,10 +15,12 @@ */ package com.diffplug.spotless.generic; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + import java.io.File; -import java.nio.charset.StandardCharsets; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.diffplug.common.io.Files; @@ -36,19 +38,19 @@ void name() throws Exception { String name = step.getName(); - Assertions.assertEquals("IDEA", name); + assertEquals("IDEA", name); } @Test void notFormattings() throws Exception { File cleanFile = newFile("clean.java"); String cleanJava = ResourceHarness.getTestResource("java/idea/full.clean.java"); - Files.write(cleanJava, cleanFile, StandardCharsets.UTF_8); + Files.write(cleanJava, cleanFile, UTF_8); FormatterStep step = IdeaStep.newBuilder(buildDir()).setUseDefaults(true).build(); var result = step.format(cleanJava, cleanFile); - Assertions.assertEquals(cleanJava, result, + assertEquals(cleanJava, result, "formatting was applied to clean file"); } @@ -56,12 +58,12 @@ void notFormattings() throws Exception { void formattings() throws Exception { File dirtyFile = newFile("dirty.java"); String dirtyJava = ResourceHarness.getTestResource("java/idea/full.dirty.java"); - Files.write(dirtyJava, dirtyFile, StandardCharsets.UTF_8); + Files.write(dirtyJava, dirtyFile, UTF_8); FormatterStep step = IdeaStep.newBuilder(buildDir()).setUseDefaults(true).build(); var result = step.format(dirtyJava, dirtyFile); - Assertions.assertNotEquals(dirtyJava, result, + assertNotEquals(dirtyJava, result, "files were not changed after reformat"); } @@ -69,12 +71,12 @@ void formattings() throws Exception { void formattingsWorkWithDefaultParameters() throws Exception { File dirtyFile = newFile("dirty.java"); String dirtyJava = ResourceHarness.getTestResource("java/idea/full.dirty.java"); - Files.write(dirtyJava, dirtyFile, StandardCharsets.UTF_8); + Files.write(dirtyJava, dirtyFile, UTF_8); FormatterStep step = IdeaStep.newBuilder(buildDir()).build(); var result = step.format(dirtyJava, dirtyFile); - Assertions.assertNotEquals(dirtyJava, result, + assertNotEquals(dirtyJava, result, "files were not changed after reformat"); } @@ -82,12 +84,12 @@ void formattingsWorkWithDefaultParameters() throws Exception { void formattingsWithoutDefaultDoesNothing() throws Exception { File dirtyFile = newFile("dirty.java"); String dirtyJava = ResourceHarness.getTestResource("java/idea/full.dirty.java"); - Files.write(dirtyJava, dirtyFile, StandardCharsets.UTF_8); + Files.write(dirtyJava, dirtyFile, UTF_8); FormatterStep step = IdeaStep.newBuilder(buildDir()).setUseDefaults(false).build(); var result = step.format(dirtyJava, dirtyFile); - Assertions.assertEquals(dirtyJava, result, + assertEquals(dirtyJava, result, "files were changed after reformat"); } @@ -95,12 +97,12 @@ void formattingsWithoutDefaultDoesNothing() throws Exception { void configureFile() throws Exception { File cleanFile = newFile("clean.java"); String cleanJava = ResourceHarness.getTestResource("java/idea/full.clean.java"); - Files.write(cleanJava, cleanFile, StandardCharsets.UTF_8); + Files.write(cleanJava, cleanFile, UTF_8); FormatterStep step = IdeaStep.newBuilder(buildDir()).setUseDefaults(true).build(); var result = step.format(cleanJava, cleanFile); - Assertions.assertEquals(cleanJava, result, + assertEquals(cleanJava, result, "formatting was applied to clean file"); } diff --git a/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java b/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java index 6bc131cbc3..a378201b82 100644 --- a/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/generic/LicenseHeaderStepTest.java @@ -15,13 +15,15 @@ */ package com.diffplug.spotless.generic; +import static java.time.ZoneOffset.UTC; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + import java.io.File; import java.io.IOException; import java.time.LocalDate; import java.time.YearMonth; -import java.time.ZoneOffset; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.diffplug.spotless.FormatterStep; @@ -185,9 +187,9 @@ private static String currentYear() { void efficient() throws Throwable { FormatterStep step = LicenseHeaderStep.headerDelimiter("LicenseHeader\n", "contentstart").build(); String alreadyCorrect = "LicenseHeader\ncontentstart"; - Assertions.assertEquals(alreadyCorrect, step.format(alreadyCorrect, new File(""))); + 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(""))); + assertSame(alreadyCorrect, step.format(alreadyCorrect, new File(""))); } @Test @@ -195,8 +197,8 @@ void sanitized() throws Throwable { // The sanitizer should add a \n FormatterStep step = LicenseHeaderStep.headerDelimiter("LicenseHeader", "contentstart").build(); String alreadyCorrect = "LicenseHeader\ncontentstart"; - Assertions.assertEquals(alreadyCorrect, step.format(alreadyCorrect, new File(""))); - Assertions.assertSame(alreadyCorrect, step.format(alreadyCorrect, new File(""))); + assertEquals(alreadyCorrect, step.format(alreadyCorrect, new File(""))); + assertSame(alreadyCorrect, step.format(alreadyCorrect, new File(""))); } @Test @@ -204,8 +206,8 @@ 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"; - Assertions.assertEquals(alreadyCorrect, step.format(alreadyCorrect, new File(""))); - Assertions.assertSame(alreadyCorrect, step.format(alreadyCorrect, new File(""))); + assertEquals(alreadyCorrect, step.format(alreadyCorrect, new File(""))); + assertSame(alreadyCorrect, step.format(alreadyCorrect, new File(""))); } @Test @@ -250,7 +252,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(); + int currentYear = LocalDate.now(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/java/GoogleJavaFormatStepTest.java b/testlib/src/test/java/com/diffplug/spotless/java/GoogleJavaFormatStepTest.java index e6e2fbdc76..d5dfcf7a86 100644 --- a/testlib/src/test/java/com/diffplug/spotless/java/GoogleJavaFormatStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/java/GoogleJavaFormatStepTest.java @@ -38,8 +38,8 @@ void jvm13Features() throws Exception { } } - @Test - @EnabledForJreRange(max = JAVA_15) // google-java-format requires JRE 11+ + @EnabledForJreRange(max = JAVA_15) + @Test // google-java-format requires JRE 11+ void behavior18() throws Exception { FormatterStep step = GoogleJavaFormatStep.create("1.8", TestProvisioner.mavenCentral()); StepHarness.forStep(step) @@ -59,8 +59,8 @@ void behavior() throws Exception { .testResource("java/googlejavaformat/JavaCodeWithPackageUnformatted.test", "java/googlejavaformat/JavaCodeWithPackageFormatted.test"); } - @Test @EnabledForJreRange(min = JAVA_21, max = JAVA_21) + @Test void versionBelowMinimumRequiredVersionIsNotAllowed() throws Exception { FormatterStep step = GoogleJavaFormatStep.create("1.2", "AOSP", TestProvisioner.mavenCentral()); StepHarness.forStepNoRoundtrip(step) @@ -68,8 +68,8 @@ void versionBelowMinimumRequiredVersionIsNotAllowed() throws Exception { .toBe("LINE_UNDEFINED google-java-format(jvm-version) You are running Spotless on JVM 21. This requires google-java-format of at least 1.17.0 (you are using 1.2). (...)"); } - @Test @EnabledForJreRange(min = JAVA_21, max = JAVA_21) + @Test void versionBelowOneDotTenIsNotAllowed() throws Exception { FormatterStep step = GoogleJavaFormatStep.create("1.9", "AOSP", TestProvisioner.mavenCentral()); StepHarness.forStepNoRoundtrip(step) @@ -132,8 +132,8 @@ void behaviorWithReorderImports() throws Exception { } } - @Test @EnabledForJreRange(max = JAVA_20) + @Test void equality() throws Exception { new SerializableEqualityTester() { String version = "1.10.0"; @@ -163,8 +163,8 @@ protected FormatterStep create() { }.testEquals(); } - @Test @EnabledForJreRange(max = JAVA_20) + @Test void equalityGroupArtifact() throws Exception { new SerializableEqualityTester() { String groupArtifact = GoogleJavaFormatStep.defaultGroupArtifact(); 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 82180045c6..d9a04aa60d 100644 --- a/testlib/src/test/java/com/diffplug/spotless/kotlin/DiktatStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/kotlin/DiktatStepTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2024 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,12 @@ package com.diffplug.spotless.kotlin; import static com.diffplug.spotless.FileSignature.signAsList; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.diffplug.spotless.FileSignature; @@ -49,12 +51,12 @@ void behaviorConf() throws Exception { @Test void notSupportedVersion() { - final IllegalStateException notSupportedException = Assertions.assertThrows(IllegalStateException.class, + final IllegalStateException notSupportedException = assertThrows(IllegalStateException.class, () -> DiktatStep.create("1.1.0", TestProvisioner.mavenCentral())); - Assertions.assertTrue( + assertTrue( notSupportedException.getMessage().contains("Minimum required Diktat version is 1.2.1, you tried 1.1.0 which is too old")); - Assertions.assertDoesNotThrow(() -> DiktatStep.create("1.2.1", TestProvisioner.mavenCentral())); - Assertions.assertDoesNotThrow(() -> DiktatStep.create("2.0.0", TestProvisioner.mavenCentral())); + assertDoesNotThrow(() -> DiktatStep.create("1.2.1", TestProvisioner.mavenCentral())); + assertDoesNotThrow(() -> DiktatStep.create("2.0.0", TestProvisioner.mavenCentral())); } } 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 da00e37d35..235dcc97c3 100644 --- a/testlib/src/test/java/com/diffplug/spotless/npm/EslintFormatterStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/npm/EslintFormatterStepTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,8 @@ @NpmTest class EslintFormatterStepTest { - @NpmTest @Nested + @NpmTest class EslintJavascriptFormattingStepTest extends NpmFormatterStepCommonTests { private final Map> devDependenciesForRuleset = ImmutableMap.of( @@ -72,8 +72,8 @@ void formattingUsingRulesetsFile(String ruleSetName) throws Exception { } } - @NpmTest @Nested + @NpmTest class EslintTypescriptFormattingStepTest extends NpmFormatterStepCommonTests { private final Map> devDependenciesForRuleset = ImmutableMap.of( @@ -114,8 +114,8 @@ void formattingUsingRulesetsFile(String ruleSetName) throws Exception { } } - @NpmTest @Nested + @NpmTest class EslintInlineConfigTypescriptFormattingStepTest extends NpmFormatterStepCommonTests { @Test diff --git a/testlib/src/test/java/com/diffplug/spotless/npm/NpmFormatterStepCommonTests.java b/testlib/src/test/java/com/diffplug/spotless/npm/NpmFormatterStepCommonTests.java index 4d59f043c7..6c810f93a0 100644 --- a/testlib/src/test/java/com/diffplug/spotless/npm/NpmFormatterStepCommonTests.java +++ b/testlib/src/test/java/com/diffplug/spotless/npm/NpmFormatterStepCommonTests.java @@ -15,8 +15,9 @@ */ package com.diffplug.spotless.npm; +import static java.util.Collections.emptyList; + import java.io.File; -import java.util.Collections; import com.diffplug.spotless.ResourceHarness; import com.diffplug.spotless.ThrowingEx; @@ -24,7 +25,7 @@ public abstract class NpmFormatterStepCommonTests extends ResourceHarness { protected NpmPathResolver npmPathResolver() { - return new NpmPathResolver(npmExecutable(), nodeExecutable(), npmrc(), Collections.emptyList()); + return new NpmPathResolver(npmExecutable(), nodeExecutable(), npmrc(), emptyList()); } private File npmExecutable() { 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 54ce09e7e8..8d2c4428b3 100644 --- a/testlib/src/test/java/com/diffplug/spotless/npm/PrettierFormatterStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/npm/PrettierFormatterStepTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,9 @@ */ package com.diffplug.spotless.npm; +import static java.util.Collections.emptyMap; + import java.io.File; -import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.Nested; @@ -39,18 +40,18 @@ class PrettierFormatterStepTest extends NpmFormatterStepCommonTests { private static final String PRETTIER_VERSION_3 = "3.0.0"; - @NpmTest @Nested + @NpmTest class PrettierFormattingOfFileTypesIsWorking extends NpmFormatterStepCommonTests { @ParameterizedTest(name = "{index}: prettier 2.x can be applied to {0}") - @ValueSource(strings = {"html", "typescript", "json", "javascript-es5", "javascript-es6", "css", "scss", "markdown", "yaml"}) + @ValueSource(strings = {"css", "html", "javascript-es5", "javascript-es6", "json", "markdown", "scss", "typescript", "yaml"}) void formattingUsingPrettier2WithConfigFile(String fileType) throws Exception { runTestUsingPrettier(fileType, PrettierFormatterStep.defaultDevDependencies()); } @ParameterizedTest(name = "{index}: prettier 3.x can be applied to {0}") - @ValueSource(strings = {"html_prettier3", "typescript", "json", "javascript-es5", "javascript-es6", "css", "scss", "markdown", "yaml"}) + @ValueSource(strings = {"css", "html_prettier3", "javascript-es5", "javascript-es6", "json", "markdown", "scss", "typescript", "yaml"}) void formattingUsingPrettier3WithConfigFile(String fileType) throws Exception { runTestUsingPrettier(fileType, ImmutableMap.of("prettier", "3.0.0")); } @@ -77,8 +78,8 @@ private void runTestUsingPrettier(String fileType, Map dependenc } } - @NpmTest @Nested + @NpmTest class SpecificPrettierFormatterStepTests extends NpmFormatterStepCommonTests { @ParameterizedTest(name = "{index}: parser inference based on explicit filepath is working with prettier {0}") @@ -118,7 +119,7 @@ void parserInferenceBasedOnFilenameIsWorking(String prettierVersion) throws Exce buildDir(), null, npmPathResolver(), - new PrettierConfig(null, Collections.emptyMap())); + new PrettierConfig(null, emptyMap())); try (StepHarnessWithFile stepHarness = StepHarnessWithFile.forStep(this, formatterStep)) { stepHarness.testResource("test.json", dirtyFile, cleanFile); @@ -142,8 +143,8 @@ void verifyPrettierErrorMessageIsRelayed() throws Exception { } } - @NpmTest @Nested + @NpmTest class PrettierFormattingOptionsAreWorking extends NpmFormatterStepCommonTests { private static final String FILEDIR = "npm/prettier/config/"; 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 969095c2f0..ee739585bc 100644 --- a/testlib/src/test/java/com/diffplug/spotless/npm/ShadowCopyTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/npm/ShadowCopyTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2023-2024 DiffPlug + * Copyright 2023-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,17 +15,18 @@ */ package com.diffplug.spotless.npm; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Comparator.comparing; +import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Arrays; -import java.util.Comparator; import java.util.List; import java.util.Random; -import java.util.stream.Collectors; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -52,7 +53,7 @@ void anAddedEntryCanBeRetrieved() throws IOException { File folderWithRandomFile = newFolderWithRandomFile(); shadowCopy.addEntry("someEntry", folderWithRandomFile); File shadowCopyFile = shadowCopy.getEntry("someEntry", folderWithRandomFile.getName()); - Assertions.assertThat(shadowCopyFile.listFiles()).hasSize(folderWithRandomFile.listFiles().length); + assertThat(shadowCopyFile.listFiles()).hasSize(folderWithRandomFile.listFiles().length); assertAllFilesAreEqualButNotSameAbsolutePath(folderWithRandomFile, shadowCopyFile); } @@ -64,8 +65,8 @@ void twoAddedEntriesCanBeRetrieved() throws IOException { shadowCopy.addEntry("someOtherEntry", folderWithRandomFile2); File shadowCopyFile = shadowCopy.getEntry("someEntry", folderWithRandomFile.getName()); File shadowCopyFile2 = shadowCopy.getEntry("someOtherEntry", folderWithRandomFile2.getName()); - Assertions.assertThat(shadowCopyFile.listFiles()).hasSize(folderWithRandomFile.listFiles().length); - Assertions.assertThat(shadowCopyFile2.listFiles()).hasSize(folderWithRandomFile2.listFiles().length); + assertThat(shadowCopyFile.listFiles()).hasSize(folderWithRandomFile.listFiles().length); + assertThat(shadowCopyFile2.listFiles()).hasSize(folderWithRandomFile2.listFiles().length); assertAllFilesAreEqualButNotSameAbsolutePath(folderWithRandomFile, shadowCopyFile); assertAllFilesAreEqualButNotSameAbsolutePath(folderWithRandomFile2, shadowCopyFile2); } @@ -76,7 +77,7 @@ void addingTheSameEntryTwiceWorks() throws IOException { shadowCopy.addEntry("someEntry", folderWithRandomFile); shadowCopy.addEntry("someEntry", folderWithRandomFile); File shadowCopyFile = shadowCopy.getEntry("someEntry", folderWithRandomFile.getName()); - Assertions.assertThat(shadowCopyFile.listFiles()).hasSize(folderWithRandomFile.listFiles().length); + assertThat(shadowCopyFile.listFiles()).hasSize(folderWithRandomFile.listFiles().length); assertAllFilesAreEqualButNotSameAbsolutePath(folderWithRandomFile, shadowCopyFile); } @@ -92,8 +93,8 @@ void changingAFolderAfterAddingItDoesNotChangeTheShadowCopy() throws IOException // now check that they are different File shadowCopy = this.shadowCopy.getEntry("someEntry", folderWithRandomFile.getName()); - Assertions.assertThat(shadowCopy.listFiles()).hasSize(folderWithRandomFile.listFiles().length); - Assertions.assertThat(shadowCopy.listFiles()[0].getName()).isNotEqualTo(folderWithRandomFile.listFiles()[0].getName()); + assertThat(shadowCopy.listFiles()).hasSize(folderWithRandomFile.listFiles().length); + assertThat(shadowCopy.listFiles()[0].getName()).isNotEqualTo(folderWithRandomFile.listFiles()[0].getName()); } @Test @@ -103,7 +104,7 @@ void aFolderCanBeCopiedUsingShadowCopy() throws IOException { File copiedFolder = newFolder("copyDest"); File copiedEntry = shadowCopy.copyEntryInto("someEntry", folderWithRandomFile.getName(), copiedFolder); - Assertions.assertThat(copiedEntry.listFiles()).hasSize(folderWithRandomFile.listFiles().length); + assertThat(copiedEntry.listFiles()).hasSize(folderWithRandomFile.listFiles().length); assertAllFilesAreEqualButNotSameAbsolutePath(folderWithRandomFile, copiedEntry); } @@ -115,7 +116,7 @@ void aCopiedFolderIsDifferentFromShadowCopyEntry() throws IOException { File copiedEntry = shadowCopy.copyEntryInto("someEntry", folderWithRandomFile.getName(), copiedFolder); File shadowCopyFile = shadowCopy.getEntry("someEntry", folderWithRandomFile.getName()); - Assertions.assertThat(shadowCopyFile.listFiles()).hasSize(copiedEntry.listFiles().length); + assertThat(shadowCopyFile.listFiles()).hasSize(copiedEntry.listFiles().length); assertAllFilesAreEqualButNotSameAbsolutePath(copiedEntry, shadowCopyFile); } @@ -123,13 +124,13 @@ void aCopiedFolderIsDifferentFromShadowCopyEntry() throws IOException { void anAddedEntryExistsAfterAdding() throws IOException { File folderWithRandomFile = newFolderWithRandomFile(); shadowCopy.addEntry("someEntry", folderWithRandomFile); - Assertions.assertThat(shadowCopy.entryExists("someEntry", folderWithRandomFile.getName())).isTrue(); + assertThat(shadowCopy.entryExists("someEntry", folderWithRandomFile.getName())).isTrue(); } @Test void aEntryThatHasNotBeenAddedDoesNotExist() throws IOException { File folderWithRandomFile = newFolderWithRandomFile(); - Assertions.assertThat(shadowCopy.entryExists("someEntry", folderWithRandomFile.getName())).isFalse(); + assertThat(shadowCopy.entryExists("someEntry", folderWithRandomFile.getName())).isFalse(); } private void assertAllFilesAreEqualButNotSameAbsolutePath(File expected, File actual) { @@ -141,8 +142,8 @@ private void assertAllFilesAreEqualButNotSameAbsolutePath(File expected, File ac } private void assertDirectoryIsEqualButNotSameAbsolutePath(File expected, File actual) { - Assertions.assertThat(actual.getAbsolutePath()).as("absolute path should be different").isNotEqualTo(expected.getAbsolutePath()); - Assertions.assertThat(actual.listFiles()).as("folder should have same amount of files").hasSize(expected.listFiles().length); + assertThat(actual.getAbsolutePath()).as("absolute path should be different").isNotEqualTo(expected.getAbsolutePath()); + assertThat(actual.listFiles()).as("folder should have same amount of files").hasSize(expected.listFiles().length); List actualContent = filesInAlphabeticalOrder(actual); List expectedContent = filesInAlphabeticalOrder(expected); @@ -156,14 +157,14 @@ private List filesInAlphabeticalOrder(File folder) { throw new IllegalArgumentException("folder must be a directory"); } return Arrays.stream(folder.listFiles()) - .sorted(Comparator.comparing(File::getName).thenComparing(File::getAbsolutePath)) - .collect(Collectors.toList()); + .sorted(comparing(File::getName).thenComparing(File::getAbsolutePath)) + .collect(toList()); } private void assertFileIsEqualButNotSameAbsolutePath(File expected, File actual) { - Assertions.assertThat(actual).as("Files have same name").hasName(expected.getName()); - Assertions.assertThat(actual.getAbsolutePath()).as("absolute path is different").isNotEqualTo(expected.getAbsolutePath()); - Assertions.assertThat(actual).as("files have same content").hasSameTextualContentAs(expected, StandardCharsets.UTF_8); + assertThat(actual).as("Files have same name").hasName(expected.getName()); + assertThat(actual.getAbsolutePath()).as("absolute path is different").isNotEqualTo(expected.getAbsolutePath()); + assertThat(actual).as("files have same content").hasSameTextualContentAs(expected, UTF_8); } private File newFolderWithRandomFile() throws IOException { @@ -174,7 +175,7 @@ private File newFolderWithRandomFile() throws IOException { } private void writeRandomStringOfLengthToFile(File file, int length) throws IOException { - Files.write(file.toPath(), randomStringOfLength(length).getBytes(StandardCharsets.UTF_8)); + Files.write(file.toPath(), randomStringOfLength(length).getBytes(UTF_8)); } private String randomStringOfLength(int length) { 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..e894313c63 100644 --- a/testlib/src/test/java/com/diffplug/spotless/npm/TsFmtFormatterStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/npm/TsFmtFormatterStepTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,11 @@ */ package com.diffplug.spotless.npm; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Collections.emptyMap; + import java.io.File; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.util.Collections; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -34,12 +35,12 @@ @NpmTest class TsFmtFormatterStepTest { - @NpmTest @Nested + @NpmTest 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"}) + @ValueSource(strings = {"tsconfig/tsconfig.json", "tsfmt/tsfmt.json", "tslint/tslint.json", "vscode/vscode.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('.')); @@ -52,7 +53,7 @@ void formattingUsingConfigFile(String formattingConfigFile) throws Exception { // 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"); Files.createDirectories(srcDir.toPath()); - Files.write(new File(srcDir, configFileNameWithoutExtension + ".ts").toPath(), getTestResource(dirtyFile).getBytes(StandardCharsets.UTF_8)); + Files.write(new File(srcDir, configFileNameWithoutExtension + ".ts").toPath(), getTestResource(dirtyFile).getBytes(UTF_8)); final FormatterStep formatterStep = TsFmtFormatterStep.create( TsFmtFormatterStep.defaultDevDependencies(), @@ -62,7 +63,7 @@ void formattingUsingConfigFile(String formattingConfigFile) throws Exception { null, npmPathResolver(), TypedTsFmtConfigFile.named(configFileNameWithoutExtension, configFile), - Collections.emptyMap()); + emptyMap()); try (StepHarness stepHarness = StepHarness.forStep(formatterStep)) { stepHarness.testResource(dirtyFile, cleanFile); @@ -70,8 +71,8 @@ void formattingUsingConfigFile(String formattingConfigFile) throws Exception { } } - @NpmTest @Nested + @NpmTest class TsFmtUsingInlineConfigTest extends NpmFormatterStepCommonTests { @Test void formattingUsingInlineConfigWorks() throws Exception { diff --git a/testlib/src/test/java/com/diffplug/spotless/rdf/RdfFormatterTest.java b/testlib/src/test/java/com/diffplug/spotless/rdf/RdfFormatterTest.java index 95ca530caa..536c1d9d3a 100644 --- a/testlib/src/test/java/com/diffplug/spotless/rdf/RdfFormatterTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/rdf/RdfFormatterTest.java @@ -15,13 +15,14 @@ */ package com.diffplug.spotless.rdf; +import static java.util.stream.Collectors.toList; + import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; @@ -92,16 +93,16 @@ private List getBeforeAfterTestResources(String beforeDir, String aft List inputs = listTestResources(beforeDir) .stream() .map(s -> Path.of(beforeDir, s)) - .collect(Collectors.toList()); + .collect(toList()); List outputs = listTestResources(afterDir) .stream() .map(s -> Path.of(afterDir, s)) - .collect(Collectors.toList()); + .collect(toList()); List missingOutputs = inputs .stream() .filter(in -> outputs .stream().noneMatch(out -> out.getFileName().equals(in.getFileName()))) - .collect(Collectors.toList()); + .collect(toList()); if (!missingOutputs.isEmpty()) { throw new IllegalStateException("'after' directory %s is missing files corresponding to these 'before' files: %s".formatted(beforeDir, missingOutputs)); } @@ -109,7 +110,7 @@ private List getBeforeAfterTestResources(String beforeDir, String aft .stream() .filter(o -> inputs .stream().noneMatch(in -> in.getFileName().equals(o.getFileName()))) - .collect(Collectors.toList()); + .collect(toList()); if (!missingInputs.isEmpty()) { throw new IllegalStateException("'before' directory %s is missing files corresponding to these 'after' files: %s".formatted(afterDir, missingInputs)); } diff --git a/testlib/src/test/java/com/diffplug/spotless/scala/ScalaFmtStepTest.java b/testlib/src/test/java/com/diffplug/spotless/scala/ScalaFmtStepTest.java index e8485c680d..1ce7f59aad 100644 --- a/testlib/src/test/java/com/diffplug/spotless/scala/ScalaFmtStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/scala/ScalaFmtStepTest.java @@ -15,9 +15,10 @@ */ package com.diffplug.spotless.scala; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + import java.io.File; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import com.diffplug.spotless.FormatterStep; @@ -57,7 +58,7 @@ void behaviorNoConfigFile() { @Test void behaviorConfigFileVersionDoesnotMatchLibrary() { FormatterStep step = ScalaFmtStep.create("3.0.0", TestProvisioner.mavenCentral(), createTestFile("scala/scalafmt/scalafmt.conf")); - Assertions.assertThatThrownBy(() -> step.format("", new File(""))).cause().message().contains("Spotless is using 3.0.0 but the config file declares 3.8.1. Both must match. Update the version declared in the plugin's settings and/or the config file."); + assertThatThrownBy(() -> step.format("", new File(""))).cause().message().contains("Spotless is using 3.0.0 but the config file declares 3.8.1. Both must match. Update the version declared in the plugin's settings and/or the config file."); } @Test @@ -92,6 +93,6 @@ protected FormatterStep create() { void invalidConfiguration() { File invalidConfFile = createTestFile("scala/scalafmt/scalafmt.invalid.conf"); Provisioner provisioner = TestProvisioner.mavenCentral(); - Assertions.assertThatThrownBy(() -> ScalaFmtStep.create("3.0.0", provisioner, invalidConfFile).format("", new File(""))).cause().message().contains("found option 'invalidScalaFmtConfigField' which wasn't expected"); + assertThatThrownBy(() -> ScalaFmtStep.create("3.0.0", provisioner, invalidConfFile).format("", new File(""))).cause().message().contains("found option 'invalidScalaFmtConfigField' which wasn't expected"); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/sql/DBeaverSQLFormatterStepTest.java b/testlib/src/test/java/com/diffplug/spotless/sql/DBeaverSQLFormatterStepTest.java index 648ddc6669..7bae06ed88 100644 --- a/testlib/src/test/java/com/diffplug/spotless/sql/DBeaverSQLFormatterStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/sql/DBeaverSQLFormatterStepTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,9 @@ */ package com.diffplug.spotless.sql; +import static java.util.Collections.emptySet; + import java.io.File; -import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; @@ -30,7 +31,7 @@ class DBeaverSQLFormatterStepTest extends ResourceHarness { @Test void behavior() { - FormatterStep step = DBeaverSQLFormatterStep.create(Collections.emptySet()); + FormatterStep step = DBeaverSQLFormatterStep.create(emptySet()); StepHarness.forStep(step) .testResource("sql/dbeaver/full.dirty", "sql/dbeaver/full.clean") .testResource("sql/dbeaver/V1_initial.sql.dirty", "sql/dbeaver/V1_initial.sql.clean")