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..4f94c0f0aa --- /dev/null +++ b/gradle/error-prone.gradle @@ -0,0 +1,263 @@ +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 + disableWarningsInGeneratedCode = true + disable( + // avoid + 'StaticImport', + // bug + 'AddNullMarkedToPackageInfo', + 'Slf4jLogStatement', + 'Slf4jLogStatement', + ) + // dev opt-in + if (!getenv().containsKey('CI') && getenv('IN_PLACE')?.toBoolean()) { + // apply + errorproneArgs.addAll( + '-XepPatchLocation:IN_PLACE', + '-XepPatchChecks:' + + '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,' + + 'DefaultCharset,' + + 'DereferenceWithNullBranch,' + + 'DirectReturn,' + + 'DiscardedPostfixExpression,' + + 'DoNotCall,' + + 'DoNotMock,' + + 'DoubleBraceInitialization,' + + 'DuplicateMapKeys,' + + 'DurationFrom,' + + 'DurationGetTemporalUnit,' + + 'DurationTemporalUnit,' + + 'DurationToLongTimeUnit,' + + 'EagerStringFormatting,' + + 'EmptyMethod,' + + 'EmptyMonoZip,' + + '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,' + + 'LexicographicalAnnotationAttributeListing,' + + 'LexicographicalAnnotationListing,' + + 'LiteByteStringUtf8,' + + 'LocalDateTemporalAmount,' + + 'LockOnBoxedPrimitive,' + + 'LoopConditionChecker,' + + 'LossyPrimitiveCompare,' + + 'MathRoundIntLong,' + + 'MislabeledAndroidString,' + + 'MisleadingEmptyVarargs,' + + 'MisleadingEscapedSpace,' + + 'MisplacedScopeAnnotations,' + + 'MissingOverride,' + + 'MissingSuperCall,' + + 'MissingTestCall,' + + 'MisusedDayOfYear,' + + 'MisusedWeekYear,' + + 'MixedDescriptors,' + + 'MockitoMockClassReference,' + + 'MockitoStubbing,' + + 'MockitoUsage,' + + 'ModifyingCollectionWithItself,' + + 'MongoDBTextFilterUsage,' + + 'MoreThanOneInjectableConstructor,' + + 'MustBeClosedChecker,' + + 'NCopiesOfChar,' + + 'NestedOptionals,' + + 'NestedPublishers,' + + 'NoCanIgnoreReturnValueOnClasses,' + + 'NonCanonicalStaticImport,' + + 'NonEmptyMono,' + + 'NonFinalCompileTimeConstant,' + + 'NonRuntimeAnnotation,' + + 'NonStaticImport,' + + 'NullArgumentForNonNullParameter,' + + 'NullTernary,' + + 'NullableOnContainingClass,' + + 'OptionalEquality,' + + 'OptionalMapUnusedValue,' + + 'OptionalOfRedundantMethod,' + + 'OptionalOrElseGet,' + + 'OverlappingQualifierAndScopeAnnotation,' + + 'OverridesJavaxInjectableMethod,' + + 'PackageInfo,' + + 'ParametersButNotParameterized,' + + 'ParcelableCreator,' + + 'PeriodFrom,' + + 'PeriodGetTemporalUnit,' + + 'PeriodTimeMath,' + + 'PreconditionsInvalidPlaceholder,' + + 'PrimitiveComparison,' + + 'PrivateSecurityContractProtoAccess,' + + 'ProtoBuilderReturnValueIgnored,' + + 'ProtoStringFieldReferenceEquality,' + + 'ProtoTruthMixedDescriptors,' + + 'ProtocolBufferOrdinal,' + + 'ProvidesMethodOutsideOfModule,' + + 'RandomCast,' + + 'RandomModInteger,' + + 'RectIntersectReturnValueIgnored,' + + 'RedundantSetterCall,' + + 'RedundantStringConversion,' + + 'RedundantStringEscape,' + + 'RefasterAnyOfUsage,' + + 'RequestMappingAnnotation,' + + 'RequestParamType,' + + 'RequiredModifiers,' + + 'RestrictedApi,' + + 'ReturnValueIgnored,' + + 'SelfAssertion,' + + 'SelfAssignment,' + + 'SelfComparison,' + + 'SelfEquals,' + + 'SetUnrecognized,' + + 'ShouldHaveEvenArgs,' + + 'SizeGreaterThanOrEqualsZero,' + + 'Slf4jLogStatement,' + + 'Slf4jLoggerDeclarationSlf4jLoggerDeclaration,' + + 'SpringMvcAnnotation,' + + 'StreamToString,' + + 'StringBuilderInitWithChar,' + + 'StringJoin,' + + 'SubstringOfZero,' + + 'SuppressWarningsDeprecated,' + + 'TemporalAccessorGetChronoField,' + + 'TestParametersNotInitialized,' + + 'TheoryButNoTheories,' + + 'ThreadBuilderNameWithPlaceholder,' + + 'ThrowIfUncheckedKnownChecked,' + + 'ThrowNull,' + + 'TimeZoneUsage,' + + 'TreeToString,' + + 'TryFailThrowable,' + + 'TypeParameterQualifier,' + + 'UnicodeDirectionalityCharacters,' + + 'UnicodeInCode,' + + 'UnnecessaryCheckNotNull,' + + 'UnnecessaryTypeArgument,' + + 'UnsafeWildcard,' + + 'UnusedAnonymousClass,' + + 'UnusedCollectionModifiedInPlace,' + + 'VarTypeName,' + + 'WrongOneof,' + + 'XorPower,' + + 'ZoneIdOfZ,' + ) + } + } +} diff --git a/gradle/sanity-check.gradle b/gradle/sanity-check.gradle new file mode 100644 index 0000000000..71e7ec68f5 --- /dev/null +++ b/gradle/sanity-check.gradle @@ -0,0 +1,287 @@ +import static java.lang.System.getenv + +// apply from: rootProject.file('gradle/spotless.gradle') +apply plugin: 'net.ltgt.errorprone' +apply plugin: 'org.openrewrite.rewrite' + +rewrite { + activeRecipe('com.diffplug.spotless.openrewrite.SanityCheck') + activeStyle('com.diffplug.spotless.openrewrite.SpotlessFormat') + exclusions.addAll( + '**.dirty.java', + '**FormatterProperties.java', + '**_gradle_node_plugin_example_**', + '**gradle/changelog.gradle', + '**gradle/java-publish.gradle', + '**idea/full.clean.java', + '**java-setup.gradle', + '**lib-extra/build.gradle', + '**lib/build.gradle', + '**package-info.java', + '**plugin-maven/build.gradle', + '**settings.gradle', + '**special-tests.gradle', + '**testlib/src/main/resources**' + ) + exportDatatables = true + failOnDryRunResults = true +} + +tasks.withType(JavaCompile).configureEach { + options.errorprone { + disableWarningsInGeneratedCode = true + disable( + // avoid + 'StaticImport', + // bug + 'AddNullMarkedToPackageInfo', + 'Slf4jLogStatement', + 'Slf4jLogStatement', + ) + // dev opt-in + if (!getenv().containsKey('CI') && getenv('IN_PLACE')?.toBoolean()) { + // apply + errorproneArgs.addAll( + '-XepPatchLocation:IN_PLACE', + '-XepPatchChecks:' + + '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,' + + 'DefaultCharset,' + + 'DereferenceWithNullBranch,' + + 'DirectReturn,' + + 'DiscardedPostfixExpression,' + + 'DoNotCall,' + + 'DoNotMock,' + + 'DoubleBraceInitialization,' + + 'DuplicateMapKeys,' + + 'DurationFrom,' + + 'DurationGetTemporalUnit,' + + 'DurationTemporalUnit,' + + 'DurationToLongTimeUnit,' + + 'EagerStringFormatting,' + + 'EmptyMethod,' + + 'EmptyMonoZip,' + + '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,' + + 'LexicographicalAnnotationAttributeListing,' + + 'LexicographicalAnnotationListing,' + + 'LiteByteStringUtf8,' + + 'LocalDateTemporalAmount,' + + 'LockOnBoxedPrimitive,' + + 'LoopConditionChecker,' + + 'LossyPrimitiveCompare,' + + 'MathRoundIntLong,' + + 'MislabeledAndroidString,' + + 'MisleadingEmptyVarargs,' + + 'MisleadingEscapedSpace,' + + 'MisplacedScopeAnnotations,' + + 'MissingOverride,' + + 'MissingSuperCall,' + + 'MissingTestCall,' + + 'MisusedDayOfYear,' + + 'MisusedWeekYear,' + + 'MixedDescriptors,' + + 'MockitoMockClassReference,' + + 'MockitoStubbing,' + + 'MockitoUsage,' + + 'ModifyingCollectionWithItself,' + + 'MongoDBTextFilterUsage,' + + 'MoreThanOneInjectableConstructor,' + + 'MustBeClosedChecker,' + + 'NCopiesOfChar,' + + 'NestedOptionals,' + + 'NestedPublishers,' + + 'NoCanIgnoreReturnValueOnClasses,' + + 'NonCanonicalStaticImport,' + + 'NonEmptyMono,' + + 'NonFinalCompileTimeConstant,' + + 'NonRuntimeAnnotation,' + + 'NonStaticImport,' + + 'NullArgumentForNonNullParameter,' + + 'NullTernary,' + + 'NullableOnContainingClass,' + + 'OptionalEquality,' + + 'OptionalMapUnusedValue,' + + 'OptionalOfRedundantMethod,' + + 'OptionalOrElseGet,' + + 'OverlappingQualifierAndScopeAnnotation,' + + 'OverridesJavaxInjectableMethod,' + + 'PackageInfo,' + + 'ParametersButNotParameterized,' + + 'ParcelableCreator,' + + 'PeriodFrom,' + + 'PeriodGetTemporalUnit,' + + 'PeriodTimeMath,' + + 'PreconditionsInvalidPlaceholder,' + + 'PrimitiveComparison,' + + 'PrivateSecurityContractProtoAccess,' + + 'ProtoBuilderReturnValueIgnored,' + + 'ProtoStringFieldReferenceEquality,' + + 'ProtoTruthMixedDescriptors,' + + 'ProtocolBufferOrdinal,' + + 'ProvidesMethodOutsideOfModule,' + + 'RandomCast,' + + 'RandomModInteger,' + + 'RectIntersectReturnValueIgnored,' + + 'RedundantSetterCall,' + + 'RedundantStringConversion,' + + 'RedundantStringEscape,' + + 'RefasterAnyOfUsage,' + + 'RequestMappingAnnotation,' + + 'RequestParamType,' + + 'RequiredModifiers,' + + 'RestrictedApi,' + + 'ReturnValueIgnored,' + + 'SelfAssertion,' + + 'SelfAssignment,' + + 'SelfComparison,' + + 'SelfEquals,' + + 'SetUnrecognized,' + + 'ShouldHaveEvenArgs,' + + 'SizeGreaterThanOrEqualsZero,' + + 'Slf4jLogStatement,' + + 'Slf4jLoggerDeclarationSlf4jLoggerDeclaration,' + + 'SpringMvcAnnotation,' + + 'StreamToString,' + + 'StringBuilderInitWithChar,' + + 'StringJoin,' + + 'SubstringOfZero,' + + 'SuppressWarningsDeprecated,' + + 'TemporalAccessorGetChronoField,' + + 'TestParametersNotInitialized,' + + 'TheoryButNoTheories,' + + 'ThreadBuilderNameWithPlaceholder,' + + 'ThrowIfUncheckedKnownChecked,' + + 'ThrowNull,' + + 'TimeZoneUsage,' + + 'TreeToString,' + + 'TryFailThrowable,' + + 'TypeParameterQualifier,' + + 'UnicodeDirectionalityCharacters,' + + 'UnicodeInCode,' + + 'UnnecessaryCheckNotNull,' + + 'UnnecessaryTypeArgument,' + + 'UnsafeWildcard,' + + 'UnusedAnonymousClass,' + + 'UnusedCollectionModifiedInPlace,' + + 'VarTypeName,' + + 'WrongOneof,' + + 'XorPower,' + + 'ZoneIdOfZ,' + ) + } + } +} + +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') +} 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/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/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..ce1a21d69d 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. @@ -115,7 +115,7 @@ public String format( private static EditorConfigOverride createEditorConfigOverride(final List rules, Map editorConfigOverrideMap) { // Get properties from rules in the rule sets Stream> ruleProperties = rules.stream() - .filter(rule -> rule instanceof UsesEditorConfigProperties) + .filter(UsesEditorConfigProperties.class::isInstance) .flatMap(rule -> ((UsesEditorConfigProperties) rule).getEditorConfigProperties().stream()); // Create a mapping of properties to their names based on rule properties and default properties 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..7e515cd62d 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. @@ -55,7 +55,7 @@ public class KtLintCompat0Dot49Dot0Adapter implements KtLintCompatAdapter { - private static final Logger logger = LoggerFactory.getLogger(KtLintCompat0Dot49Dot0Adapter.class); + private static final Logger LOGGER = LoggerFactory.getLogger(KtLintCompat0Dot49Dot0Adapter.class); private static final List> DEFAULT_EDITOR_CONFIG_PROPERTIES; diff --git a/lib/src/compatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0Adapter.java b/lib/src/compatKtLint0Dot50Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat0Dot50Dot0Adapter.java index 951b82704a..437b9579bd 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. @@ -55,7 +55,7 @@ public class KtLintCompat0Dot50Dot0Adapter implements KtLintCompatAdapter { - private static final Logger logger = LoggerFactory.getLogger(KtLintCompat0Dot50Dot0Adapter.class); + private static final Logger LOGGER = LoggerFactory.getLogger(KtLintCompat0Dot50Dot0Adapter.class); private static final List> DEFAULT_EDITOR_CONFIG_PROPERTIES; diff --git a/lib/src/compatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0Adapter.java b/lib/src/compatKtLint1Dot0Dot0/java/com/diffplug/spotless/glue/ktlint/compat/KtLintCompat1Dot0Dot0Adapter.java index 86387d0d6b..8bf029a59a 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. @@ -54,7 +54,7 @@ public class KtLintCompat1Dot0Dot0Adapter implements KtLintCompatAdapter { - private static final Logger logger = LoggerFactory.getLogger(KtLintCompat1Dot0Dot0Adapter.class); + private static final Logger LOGGER = LoggerFactory.getLogger(KtLintCompat1Dot0Dot0Adapter.class); private static final List> DEFAULT_EDITOR_CONFIG_PROPERTIES; diff --git a/lib/src/googleJavaFormat/java/com/diffplug/spotless/glue/java/GoogleJavaFormatFormatterFunc.java b/lib/src/googleJavaFormat/java/com/diffplug/spotless/glue/java/GoogleJavaFormatFormatterFunc.java index d13f8d9d40..fba3e7fafc 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. @@ -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..de0f136bdc 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. @@ -32,8 +32,8 @@ public GoogleJavaFormatRemoveUnusedImporterFormatterFunc(@Nonnull String version this.version = Objects.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/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java b/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java index 4b8308e47c..8c8220053f 100644 --- a/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java +++ b/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java @@ -63,13 +63,13 @@ private FormattingOptions createFormattingOptions() throws Exception { if (ktfmtFormattingOptions != null) { formattingOptions = formattingOptions.copy( - ktfmtFormattingOptions.getMaxWidth().orElse(formattingOptions.getMaxWidth()), - ktfmtFormattingOptions.getBlockIndent().orElse(formattingOptions.getBlockIndent()), - ktfmtFormattingOptions.getContinuationIndent().orElse(formattingOptions.getContinuationIndent()), + ktfmtFormattingOptions.getMaxWidth().orElseGet(formattingOptions::getMaxWidth), + ktfmtFormattingOptions.getBlockIndent().orElseGet(formattingOptions::getBlockIndent), + ktfmtFormattingOptions.getContinuationIndent().orElseGet(formattingOptions::getContinuationIndent), ktfmtFormattingOptions.getTrailingCommaManagementStrategy() .map(KtfmtTrailingCommaManagementStrategy::toFormatterTrailingCommaManagementStrategy) - .orElse(formattingOptions.getTrailingCommaManagementStrategy()), - ktfmtFormattingOptions.getRemoveUnusedImports().orElse(formattingOptions.getRemoveUnusedImports()), + .orElseGet(formattingOptions::getTrailingCommaManagementStrategy), + ktfmtFormattingOptions.getRemoveUnusedImports().orElseGet(formattingOptions::getRemoveUnusedImports), formattingOptions.getDebuggingPrintOpsAfterFormatting()); } diff --git a/lib/src/main/java/com/diffplug/spotless/FileSignature.java b/lib/src/main/java/com/diffplug/spotless/FileSignature.java index f0332aef1f..628447119d 100644 --- a/lib/src/main/java/com/diffplug/spotless/FileSignature.java +++ b/lib/src/main/java/com/diffplug/spotless/FileSignature.java @@ -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; @@ -146,11 +145,11 @@ public File getOnlyFile() { } } - private static final boolean machineIsWin = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win"); + private static final boolean MACHINE_IS_WIN = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win"); /** Returns true if this JVM is running on a windows machine. */ public static boolean machineIsWin() { - return machineIsWin; + return MACHINE_IS_WIN; } /** Transforms a native path to a unix one. */ diff --git a/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java index 9041bdb6c5..df58012702 100644 --- a/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java @@ -33,8 +33,7 @@ final class FilterByContentPatternFormatterStep extends DelegateFormatterStep { this.contentPattern = Pattern.compile(Objects.requireNonNull(contentPattern)); } - @Override - public @Nullable String format(String raw, File file) throws Exception { + @Nullable public @Override String format(String raw, File file) throws Exception { Objects.requireNonNull(raw, "raw"); Objects.requireNonNull(file, "file"); if (contentPattern.matcher(raw).find() == (onMatch == OnMatch.INCLUDE)) { diff --git a/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java index 7de0a32fbc..ecb0dd203f 100644 --- a/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java @@ -30,8 +30,7 @@ final class FilterByFileFormatterStep extends DelegateFormatterStep { this.filter = Objects.requireNonNull(filter); } - @Override - public @Nullable String format(String raw, File file) throws Exception { + @Nullable public @Override String format(String raw, File file) throws Exception { Objects.requireNonNull(raw, "raw"); Objects.requireNonNull(file, "file"); if (filter.accept(file)) { diff --git a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java index d205e14039..8697ca68c3 100644 --- a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java +++ b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java @@ -134,7 +134,7 @@ private RuntimeException exceptionFmt(String msgPrimary, ProcessRunner.Result cm errorMsg.append(msgFix); errorMsg.append('\n'); } - errorMsg.append(cmd.toString()); + errorMsg.append(cmd); return new RuntimeException(errorMsg.toString()); } } diff --git a/lib/src/main/java/com/diffplug/spotless/Formatter.java b/lib/src/main/java/com/diffplug/spotless/Formatter.java index 941667adb4..b0ec2cbd6b 100644 --- a/lib/src/main/java/com/diffplug/spotless/Formatter.java +++ b/lib/src/main/java/com/diffplug/spotless/Formatter.java @@ -143,13 +143,13 @@ static void legacyErrorBehavior(Formatter formatter, File file, ValuePerStep> toFormat) { /** Should use {@link #createPolicy(File, Supplier)} instead, but this will work iff its a path-independent LineEnding policy. */ public Policy createPolicy() { switch (this) { - case PLATFORM_NATIVE: return _platformNativePolicy; + case PLATFORM_NATIVE: return _PLATFORM_NATIVE_POLICY; case WINDOWS: return WINDOWS_POLICY; case UNIX: return UNIX_POLICY; case MAC_CLASSIC: return MAC_CLASSIC_POLICY; @@ -152,9 +152,9 @@ static String getEndingFor(Reader reader) throws IOException { private static final Policy UNIX_POLICY = new ConstantLineEndingPolicy(UNIX.str()); private static final Policy MAC_CLASSIC_POLICY = new ConstantLineEndingPolicy(MAC_CLASSIC.str()); private static final Policy PRESERVE_POLICY = new PreserveLineEndingPolicy(); - private static final String _platformNative = System.getProperty("line.separator"); - private static final Policy _platformNativePolicy = new ConstantLineEndingPolicy(_platformNative); - private static final boolean nativeIsWin = _platformNative.equals(WINDOWS.str()); + private static final String _PLATFORM_NATIVE = System.getProperty("line.separator"); + private static final Policy _PLATFORM_NATIVE_POLICY = new ConstantLineEndingPolicy(_PLATFORM_NATIVE); + private static final boolean NATIVE_IS_WIN = _PLATFORM_NATIVE.equals(WINDOWS.str()); /** * @deprecated Using the system-native line endings to detect the windows operating system has turned out @@ -164,13 +164,13 @@ static String getEndingFor(Reader reader) throws IOException { */ @Deprecated public static boolean nativeIsWin() { - return nativeIsWin; + return NATIVE_IS_WIN; } /** Returns the standard line ending for this policy. */ public String str() { switch (this) { - case PLATFORM_NATIVE: return _platformNative; + case PLATFORM_NATIVE: return _PLATFORM_NATIVE; case WINDOWS: return "\r\n"; case UNIX: return "\n"; case MAC_CLASSIC: return "\r"; diff --git a/lib/src/main/java/com/diffplug/spotless/LintState.java b/lib/src/main/java/com/diffplug/spotless/LintState.java index bc4cf9e64b..b025ea3caa 100644 --- a/lib/src/main/java/com/diffplug/spotless/LintState.java +++ b/lib/src/main/java/com/diffplug/spotless/LintState.java @@ -197,10 +197,10 @@ public static LintState of(Formatter formatter, File file, byte[] rawBytes) { /** Returns the DirtyState which corresponds to {@code isClean()}. */ public static LintState clean() { - return isClean; + return IS_CLEAN; } - private static final LintState isClean = new LintState(DirtyState.clean(), null); + private static final LintState IS_CLEAN = new LintState(DirtyState.clean(), null); static Throwable formatStepCausedNoChange() { return FormatterCausedNoChange.INSTANCE; diff --git a/lib/src/main/java/com/diffplug/spotless/PaddedCell.java b/lib/src/main/java/com/diffplug/spotless/PaddedCell.java index 18fb44acbb..f6973a6daa 100644 --- a/lib/src/main/java/com/diffplug/spotless/PaddedCell.java +++ b/lib/src/main/java/com/diffplug/spotless/PaddedCell.java @@ -153,7 +153,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, Comparator.comparingInt(String::length).thenComparing(Function.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/RingBufferByteArrayOutputStream.java b/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java index 86b7ecc370..74ccfabb47 100644 --- a/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java +++ b/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless; +import static java.nio.charset.StandardCharsets.UTF_8; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -115,13 +117,13 @@ 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(); + return super.toString(UTF_8); } - return new String(buf, zeroIndexPointer, limit - zeroIndexPointer) + new String(buf, 0, zeroIndexPointer); + return new String(buf, zeroIndexPointer, limit - zeroIndexPointer, UTF_8) + new String(buf, 0, zeroIndexPointer, UTF_8); } @Override diff --git a/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java b/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java index 82cdd5d3c2..795f33f6e4 100644 --- a/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java +++ b/lib/src/main/java/com/diffplug/spotless/SpotlessCache.java @@ -76,7 +76,7 @@ synchronized ClassLoader classloader(Serializable key, JarState state) { } static SpotlessCache instance() { - return instance; + return INSTANCE; } /** @@ -84,9 +84,9 @@ static SpotlessCache instance() { */ private static void clear() { List toDelete; - synchronized (instance) { - toDelete = new ArrayList<>(instance.cache.values()); - instance.cache.clear(); + synchronized (INSTANCE) { + toDelete = new ArrayList<>(INSTANCE.cache.values()); + INSTANCE.cache.clear(); } for (URLClassLoader classLoader : toDelete) { try { @@ -104,7 +104,7 @@ private static void clear() { * If {@code key} is null, the clear will always happen (as though null != null). */ public static boolean clearOnce(@Nullable Object key) { - synchronized (instance) { + synchronized (INSTANCE) { if (key == null) { lastClear = null; } else if (key.equals(lastClear)) { @@ -117,5 +117,5 @@ public static boolean clearOnce(@Nullable Object key) { return true; } - private static final SpotlessCache instance = new SpotlessCache(); + private static final SpotlessCache INSTANCE = new SpotlessCache(); } diff --git a/lib/src/main/java/com/diffplug/spotless/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..0b2b1a6575 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java @@ -42,7 +42,7 @@ * https://github.com/biomejs/biome. */ final class BiomeExecutableDownloader { - private static final Logger logger = LoggerFactory.getLogger(BiomeExecutableDownloader.class); + private static final Logger LOGGER = LoggerFactory.getLogger(BiomeExecutableDownloader.class); /** * The checksum algorithm to use for checking the integrity of downloaded files. @@ -106,7 +106,7 @@ public Path download(String version) throws IOException, InterruptedException { if (executableDir != null) { Files.createDirectories(executableDir); } - logger.info("Attempting to download Biome from '{}' to '{}'", url, executablePath); + LOGGER.info("Attempting to download Biome from '{}' to '{}'", url, executablePath); var request = HttpRequest.newBuilder(URI.create(url)).GET().build(); var handler = BodyHandlers.ofFile(executablePath, WRITE_OPTIONS); var response = HttpClient.newBuilder().followRedirects(Redirect.NORMAL).build().send(request, handler); @@ -118,7 +118,7 @@ public Path download(String version) throws IOException, InterruptedException { throw new IOException("Failed to download file from " + url + ", file is empty or does not exist"); } writeChecksumFile(downloadedFile, checksumPath); - logger.debug("Biome was downloaded successfully to '{}'", downloadedFile); + LOGGER.debug("Biome was downloaded successfully to '{}'", downloadedFile); return downloadedFile; } @@ -142,13 +142,13 @@ public Path download(String version) throws IOException, InterruptedException { */ public Path ensureDownloaded(String version) throws IOException, InterruptedException { var platform = Platform.guess(); - logger.debug("Ensuring that Biome for platform '{}' is downloaded", platform); + LOGGER.debug("Ensuring that Biome for platform '{}' is downloaded", platform); var existing = findDownloaded(version); if (existing.isPresent()) { - logger.debug("Biome was already downloaded, using executable at '{}'", existing.orElseThrow()); + LOGGER.debug("Biome was already downloaded, using executable at '{}'", existing.orElseThrow()); return existing.orElseThrow(); } else { - logger.debug("Biome was not yet downloaded, attempting to download executable"); + LOGGER.debug("Biome was not yet downloaded, attempting to download executable"); return download(version); } } @@ -169,7 +169,7 @@ public Path ensureDownloaded(String version) throws IOException, InterruptedExce public Optional findDownloaded(String version) throws IOException { var platform = Platform.guess(); var executablePath = getExecutablePath(version, platform); - logger.debug("Checking Biome executable at {}", executablePath); + LOGGER.debug("Checking Biome executable at {}", executablePath); return checkFileWithChecksum(executablePath) ? Optional.ofNullable(executablePath) : Optional.empty(); } @@ -183,26 +183,26 @@ public Optional findDownloaded(String version) throws IOException { */ private boolean checkFileWithChecksum(Path filePath) { if (!Files.exists(filePath)) { - logger.debug("File '{}' does not exist yet", filePath); + LOGGER.debug("File '{}' does not exist yet", filePath); return false; } if (Files.isDirectory(filePath)) { - logger.debug("File '{}' exists, but is a directory", filePath); + LOGGER.debug("File '{}' exists, but is a directory", filePath); return false; } var checksumPath = getChecksumPath(filePath); if (!Files.exists(checksumPath)) { - logger.debug("File '{}' exists, but checksum file '{}' does not", filePath, checksumPath); + LOGGER.debug("File '{}' exists, but checksum file '{}' does not", filePath, checksumPath); return false; } if (Files.isDirectory(checksumPath)) { - logger.debug("Checksum file '{}' exists, but is a directory", checksumPath); + LOGGER.debug("Checksum file '{}' exists, but is a directory", checksumPath); return false; } try { var actualChecksum = computeChecksum(filePath, CHECKSUM_ALGORITHM); var expectedChecksum = readTextFile(checksumPath, StandardCharsets.ISO_8859_1); - logger.debug("Expected checksum: {}, actual checksum: {}", expectedChecksum, actualChecksum); + LOGGER.debug("Expected checksum: {}, actual checksum: {}", expectedChecksum, actualChecksum); return Objects.equals(expectedChecksum, actualChecksum); } catch (final IOException ignored) { return false; @@ -261,7 +261,7 @@ private Path getChecksumPath(Path file) { var parent = file.getParent(); var base = parent != null ? parent : file; var fileName = file.getFileName(); - var checksumName = fileName != null ? fileName.toString() + ".sha256" : "checksum.sha256"; + var checksumName = fileName != null ? fileName + ".sha256" : "checksum.sha256"; return base.resolve(checksumName); } diff --git a/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java b/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java index 6d1db090b3..44948a1294 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeSettings.java @@ -22,7 +22,7 @@ * Settings and constants for Biome to use. */ public final class BiomeSettings { - private static final Logger logger = LoggerFactory.getLogger(BiomeSettings.class); + private static final Logger LOGGER = LoggerFactory.getLogger(BiomeSettings.class); private static final String CONFIG_NAME = "biome.json"; private static final String DEFAULT_VERSION = "1.2.0"; @@ -106,7 +106,7 @@ public static boolean versionHigherThanOrEqualTo(String version, int major, int } return actualMajor == major && actualMinor == minor && actualPatch == patch; } catch (final Exception e) { - logger.warn("Failed to parse biome version string '{}'. Expected format is 'major.minor.patch'.", version, e); + LOGGER.warn("Failed to parse biome version string '{}'. Expected format is 'major.minor.patch'.", version, e); return false; } } diff --git a/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java b/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java index 66b69112d5..848481e07e 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java @@ -25,7 +25,6 @@ import java.nio.file.attribute.PosixFilePermission; import java.util.ArrayList; import java.util.HashSet; -import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,7 +42,7 @@ * the network when no executable path is provided explicitly. */ public final class BiomeStep { - private static final Logger logger = LoggerFactory.getLogger(BiomeStep.class); + private static final Logger LOGGER = LoggerFactory.getLogger(BiomeStep.class); /** * Path to the directory with the {@code biome.json} config file, can be @@ -136,7 +135,7 @@ private static void attemptToAddPosixPermission(Path file, PosixFilePermission p newPermissions.add(permission); Files.setPosixFilePermissions(file, newPermissions); } catch (final Exception ignore) { - logger.debug("Unable to add POSIX permission '{}' to file '{}'", permission, file); + LOGGER.debug("Unable to add POSIX permission '{}' to file '{}'", permission, file); } } @@ -298,8 +297,8 @@ private State createState() throws IOException, InterruptedException { var resolvedPathToExe = resolveExe(); validateBiomeExecutable(resolvedPathToExe); validateBiomeConfigPath(configPath, version); - logger.debug("Using Biome executable located at '{}'", resolvedPathToExe); - var exeSignature = FileSignature.signAsList(Set.of(new File(resolvedPathToExe))); + LOGGER.debug("Using Biome executable located at '{}'", resolvedPathToExe); + var exeSignature = FileSignature.signAsList(new File(resolvedPathToExe)); makeExecutable(resolvedPathToExe); return new State(resolvedPathToExe, exeSignature, configPath, language); } @@ -421,13 +420,13 @@ private String[] buildBiomeCommand(File file) { private String format(ProcessRunner runner, String input, File file) throws IOException, InterruptedException { var stdin = input.getBytes(StandardCharsets.UTF_8); var args = buildBiomeCommand(file); - if (logger.isDebugEnabled()) { - logger.debug("Running Biome command to format code: '{}'", String.join(", ", args)); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Running Biome command to format code: '{}'", String.join(", ", args)); } var runnerResult = runner.exec(stdin, args); var stdErr = runnerResult.stdErrUtf8(); if (!stdErr.isEmpty()) { - logger.warn("Biome stderr ouptut for file '{}'\n{}", file, stdErr.trim()); + LOGGER.warn("Biome stderr ouptut for file '{}'\n{}", file, stdErr.trim()); } var formatted = runnerResult.assertExitZero(StandardCharsets.UTF_8); // When biome encounters an ignored file, it does not output any formatted code diff --git a/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java b/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java index 51350473a6..d7a62341c3 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,8 @@ */ package com.diffplug.spotless.generic; +import static java.nio.charset.StandardCharsets.UTF_8; + import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -482,7 +484,7 @@ private static String drain(InputStream stream) throws IOException { while ((numRead = stream.read(buf)) != -1) { output.write(buf, 0, numRead); } - return new String(output.toByteArray()); + return new String(output.toByteArray(), UTF_8); } } } diff --git a/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java b/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java index bfdfc0ba09..587f3827ba 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java @@ -47,7 +47,7 @@ public final class FormatAnnotationsStep implements Serializable { * A type annotation is an annotation that is meta-annotated with @Target({ElementType.TYPE_USE}). * A type annotation should be formatted on the same line as the type it qualifies. */ - private static final List defaultTypeAnnotations = + private static final List DEFAULT_TYPE_ANNOTATIONS = // Use simple names because Spotless has no access to the // fully-qualified names or the definitions of the type qualifiers. Arrays.asList( @@ -431,21 +431,21 @@ private static final class State implements Serializable { @Serial private static final long serialVersionUID = 1L; - private final Set typeAnnotations = new HashSet<>(defaultTypeAnnotations); + private final Set typeAnnotations = new HashSet<>(DEFAULT_TYPE_ANNOTATIONS); // group 1 is the basename of the annotation. - private static final String annoNoArgRegex = "@(?:[A-Za-z_][A-Za-z0-9_.]*\\.)?([A-Za-z_][A-Za-z0-9_]*)"; + private static final String ANNO_NO_ARG_REGEX = "@(?:[A-Za-z_][A-Za-z0-9_.]*\\.)?([A-Za-z_][A-Za-z0-9_]*)"; // 3 non-empty cases: () (".*") (.*) - private static final String annoArgRegex = "(?:\\(\\)|\\(\"[^\"]*\"\\)|\\([^\")][^)]*\\))?"; + private static final String ANNO_ARG_REGEX = "(?:\\(\\)|\\(\"[^\"]*\"\\)|\\([^\")][^)]*\\))?"; // group 1 is the basename of the annotation. - private static final String annoRegex = annoNoArgRegex + annoArgRegex; - private static final String trailingAnnoRegex = annoRegex + "$"; - private static final Pattern trailingAnnoPattern = Pattern.compile(trailingAnnoRegex); + private static final String ANNO_REGEX = ANNO_NO_ARG_REGEX + ANNO_ARG_REGEX; + private static final String TRAILING_ANNO_REGEX = ANNO_REGEX + "$"; + private static final Pattern TRAILING_ANNO_PATTERN = Pattern.compile(TRAILING_ANNO_REGEX); // Heuristic: matches if the line might be within a //, /*, or Javadoc comment. - private static final Pattern withinCommentPattern = Pattern.compile("//|/\\*(?!.*/*/)|^[ \t]*\\*[ \t]"); + private static final Pattern WITHIN_COMMENT_PATTERN = Pattern.compile("//|/\\*(?!.*/*/)|^[ \t]*\\*[ \t]"); // Don't move an annotation to the start of a comment line. - private static final Pattern startsWithCommentPattern = Pattern.compile("^[ \t]*(//|/\\*$|/\\*|void\\b)"); + private static final Pattern STARTS_WITH_COMMENT_PATTERN = Pattern.compile("^[ \t]*(//|/\\*$|/\\*|void\\b)"); /** * @param addedTypeAnnotations simple names to add to Spotless's default list @@ -473,7 +473,7 @@ String fixupTypeAnnotations(String unixStr) { String line = lines[i]; if (endsWithTypeAnnotation(line)) { String nextLine = lines[i + 1]; - if (startsWithCommentPattern.matcher(nextLine).find()) { + if (STARTS_WITH_COMMENT_PATTERN.matcher(nextLine).find()) { continue; } lines[i] = ""; @@ -490,14 +490,14 @@ String fixupTypeAnnotations(String unixStr) { boolean endsWithTypeAnnotation(String unixLine) { // Remove trailing newline. String line = unixLine.replaceAll("\\s+$", ""); - Matcher m = trailingAnnoPattern.matcher(line); + Matcher m = TRAILING_ANNO_PATTERN.matcher(line); if (!m.find()) { return false; } String preceding = line.substring(0, m.start()); String basename = m.group(1); - if (withinCommentPattern.matcher(preceding).find()) { + if (WITHIN_COMMENT_PATTERN.matcher(preceding).find()) { return false; } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java index 04c07e793f..71d2406b57 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java @@ -40,7 +40,7 @@ public final class EslintFormatterStep { - private static final Logger logger = LoggerFactory.getLogger(EslintFormatterStep.class); + private static final Logger LOGGER = LoggerFactory.getLogger(EslintFormatterStep.class); public static final String NAME = "eslint-format"; @@ -109,17 +109,17 @@ protected void prepareNodeServerLayout(NodeServerLayout nodeServerLayout) throws // If any config files are provided, we need to make sure they are at the same location as the node modules // as eslint will try to resolve plugin/config names relatively to the config file location and some // eslint configs contain relative paths to additional config files (such as tsconfig.json e.g.) - logger.debug("Copying config file <{}> to <{}> and using the copy", origEslintConfig.getEslintConfigPath(), nodeServerLayout.nodeModulesDir()); + LOGGER.debug("Copying config file <{}> to <{}> and using the copy", origEslintConfig.getEslintConfigPath(), nodeServerLayout.nodeModulesDir()); File configFileCopy = NpmResourceHelper.copyFileToDir(origEslintConfig.getEslintConfigPath(), nodeServerLayout.nodeModulesDir()); this.eslintConfigInUse = this.origEslintConfig.withEslintConfigPath(configFileCopy).verify(); } } - @Override @Nonnull + @Override public FormatterFunc createFormatterFunc() { try { - logger.info("Creating formatter function (starting server)"); + LOGGER.info("Creating formatter function (starting server)"); Runtime runtime = toRuntime(); ServerProcessInfo eslintRestServer = runtime.npmRunServer(); EslintRestService restService = new EslintRestService(eslintRestServer.getBaseUrl()); @@ -130,11 +130,11 @@ public FormatterFunc createFormatterFunc() { } private void endServer(BaseNpmRestService restService, ServerProcessInfo restServer) throws Exception { - logger.info("Closing formatting function (ending server)."); + LOGGER.info("Closing formatting function (ending server)."); try { restService.shutdown(); } catch (Throwable t) { - logger.info("Failed to request shutdown of rest service via api. Trying via process.", t); + LOGGER.info("Failed to request shutdown of rest service via api. Trying via process.", t); } restServer.close(); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java b/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java index 2b8c542ba8..8965e700b2 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java @@ -39,7 +39,7 @@ static ExclusiveFolderAccess forFolder(@Nonnull String path) { final class ExclusiveFolderAccessSharedMutex implements ExclusiveFolderAccess { - private static final ConcurrentHashMap mutexes = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap MUTEXES = new ConcurrentHashMap<>(); private final String path; @@ -48,7 +48,7 @@ private ExclusiveFolderAccessSharedMutex(@Nonnull String path) { } private Lock getMutex() { - return mutexes.computeIfAbsent(path, k -> new ReentrantLock()); + return MUTEXES.computeIfAbsent(path, k -> new ReentrantLock()); } @Override diff --git a/lib/src/main/java/com/diffplug/spotless/npm/ListableAdapter.java b/lib/src/main/java/com/diffplug/spotless/npm/ListableAdapter.java index aa4a96b885..d9007948f2 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/ListableAdapter.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/ListableAdapter.java @@ -45,8 +45,8 @@ static Iterable adapt(Object delegate) { return new ListableAdapter<>(delegate); } - @Override @Nonnull + @Override public Iterator iterator() { return delegate.iterator(); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeApp.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeApp.java index 19eb584c57..ffe8e2bf13 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeApp.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeApp.java @@ -29,9 +29,9 @@ public class NodeApp { - private static final Logger logger = LoggerFactory.getLogger(NodeApp.class); + private static final Logger LOGGER = LoggerFactory.getLogger(NodeApp.class); - private static final TimedLogger timedLogger = TimedLogger.forLogger(logger); + private static final TimedLogger TIMED_LOGGER = TimedLogger.forLogger(LOGGER); @Nonnull protected final NodeServerLayout nodeServerLayout; @@ -54,10 +54,10 @@ public NodeApp(@Nonnull NodeServerLayout nodeServerLayout, @Nonnull NpmConfig np private static NpmProcessFactory processFactory(NpmFormatterStepLocations formatterStepLocations) { if (formatterStepLocations.cacheDir() != null) { - logger.info("Caching npm install results in {}.", formatterStepLocations.cacheDir()); + LOGGER.info("Caching npm install results in {}.", formatterStepLocations.cacheDir()); return NodeModulesCachingNpmProcessFactory.create(formatterStepLocations.cacheDir()); } - logger.debug("Not caching npm install results."); + LOGGER.debug("Not caching npm install results."); return StandardNpmProcessFactory.INSTANCE; } @@ -70,7 +70,7 @@ boolean needsPrepareNodeAppLayout() { } void prepareNodeAppLayout() { - timedLogger.withInfo("Preparing {} for npm step {}.", this.nodeServerLayout, getClass().getName()).run(() -> { + TIMED_LOGGER.withInfo("Preparing {} for npm step {}.", this.nodeServerLayout, getClass().getName()).run(() -> { NpmResourceHelper.assertDirectoryExists(nodeServerLayout.nodeModulesDir()); NpmResourceHelper.writeUtf8StringToFile(nodeServerLayout.packageJsonFile(), this.npmConfig.getPackageJsonContent()); if (this.npmConfig.getServeScriptContent() != null) { @@ -87,7 +87,7 @@ void prepareNodeAppLayout() { } void npmInstall() { - timedLogger.withInfo("Installing npm dependencies for {} with {}.", this.nodeServerLayout, this.npmProcessFactory.describe()) + TIMED_LOGGER.withInfo("Installing npm dependencies for {} with {}.", this.nodeServerLayout, this.npmProcessFactory.describe()) .run(this::optimizedNpmInstall); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java index ae8ff3afa8..c483e0c1e2 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java @@ -29,9 +29,9 @@ public final class NodeModulesCachingNpmProcessFactory implements NpmProcessFactory { - private static final Logger logger = LoggerFactory.getLogger(NodeModulesCachingNpmProcessFactory.class); + private static final Logger LOGGER = LoggerFactory.getLogger(NodeModulesCachingNpmProcessFactory.class); - private static final TimedLogger timedLogger = TimedLogger.forLogger(logger); + private static final TimedLogger TIMED_LOGGER = TimedLogger.forLogger(LOGGER); private final File cacheDir; @@ -84,11 +84,11 @@ public CachingNmpInstall(NpmProcess actualNpmInstallProcess, NodeServerLayout no public Result waitFor() { String entryName = entryName(); if (shadowCopy.entryExists(entryName, NodeServerLayout.NODE_MODULES)) { - timedLogger.withInfo("Using cached node_modules for {} from {}", entryName, cacheDir) + TIMED_LOGGER.withInfo("Using cached node_modules for {} from {}", entryName, cacheDir) .run(() -> shadowCopy.copyEntryInto(entryName(), NodeServerLayout.NODE_MODULES, nodeServerLayout.nodeModulesDir())); return new CachedResult(); } else { - Result result = timedLogger.withInfo("calling actual npm install {}", actualNpmInstallProcess.describe()) + Result result = TIMED_LOGGER.withInfo("calling actual npm install {}", actualNpmInstallProcess.describe()) .call(actualNpmInstallProcess::waitFor); assert result.exitCode() == 0; storeShadowCopy(entryName); @@ -97,7 +97,7 @@ public Result waitFor() { } private void storeShadowCopy(String entryName) { - timedLogger.withInfo("Caching node_modules for {} in {}", entryName, cacheDir) + TIMED_LOGGER.withInfo("Caching node_modules for {} in {}", entryName, cacheDir) .run(() -> shadowCopy.addEntry(entryName(), new File(nodeServerLayout.nodeModulesDir(), NodeServerLayout.NODE_MODULES))); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeServeApp.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeServeApp.java index 3e2efd43e8..c457807560 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeServeApp.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeServeApp.java @@ -26,16 +26,16 @@ public class NodeServeApp extends NodeApp { - private static final Logger logger = LoggerFactory.getLogger(NodeApp.class); + private static final Logger LOGGER = LoggerFactory.getLogger(NodeApp.class); - private static final TimedLogger timedLogger = TimedLogger.forLogger(logger); + private static final TimedLogger TIMED_LOGGER = TimedLogger.forLogger(LOGGER); public NodeServeApp(@Nonnull NodeServerLayout nodeServerLayout, @Nonnull NpmConfig npmConfig, @Nonnull NpmFormatterStepLocations formatterStepLocations) { super(nodeServerLayout, npmConfig, formatterStepLocations); } ProcessRunner.LongRunningProcess startNpmServeProcess(UUID nodeServerInstanceId) { - return timedLogger.withInfo("Starting npm based server in {} with {}.", this.nodeServerLayout.nodeModulesDir(), this.npmProcessFactory.describe()) + return TIMED_LOGGER.withInfo("Starting npm based server in {} with {}.", this.nodeServerLayout.nodeModulesDir(), this.npmProcessFactory.describe()) .call(() -> npmProcessFactory.createNpmServeProcess(nodeServerLayout, formatterStepLocations, nodeServerInstanceId).start()); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java index dcd79d1ee0..7fc8f2033b 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java @@ -39,9 +39,9 @@ abstract class NpmFormatterStepStateBase implements Serializable { - private static final Logger logger = LoggerFactory.getLogger(NpmFormatterStepStateBase.class); + private static final Logger LOGGER = LoggerFactory.getLogger(NpmFormatterStepStateBase.class); - private static final TimedLogger timedLogger = TimedLogger.forLogger(logger); + private static final TimedLogger TIMED_LOGGER = TimedLogger.forLogger(LOGGER); @Serial private static final long serialVersionUID = 1460749955865959948L; @@ -132,11 +132,11 @@ protected ServerProcessInfo npmRunServer() throws ServerStartException, IOExcept if (server.isAlive()) { server.destroyForcibly(); ProcessRunner.Result result = server.result(); - logger.info("Launching npm server process failed. Process result:\n{}", result); + LOGGER.info("Launching npm server process failed. Process result:\n{}", result); } } catch (Throwable t) { ProcessRunner.Result result = ThrowingEx.get(server::result); - logger.debug("Unable to forcibly end the server process. Process result:\n{}", result, t); + LOGGER.debug("Unable to forcibly end the server process. Process result:\n{}", result, t); } throw timeoutException; } @@ -194,15 +194,15 @@ public String getBaseUrl() { @Override public void close() throws Exception { try { - logger.trace("Closing npm server in directory <{}> and port <{}>", + LOGGER.trace("Closing npm server in directory <{}> and port <{}>", serverPortFile.getParent(), serverPort); if (server.isAlive()) { boolean ended = server.waitFor(5, TimeUnit.SECONDS); if (!ended) { - logger.info("Force-Closing npm server in directory <{}> and port <{}>", serverPortFile.getParent(), serverPort); + LOGGER.info("Force-Closing npm server in directory <{}> and port <{}>", serverPortFile.getParent(), serverPort); server.destroyForcibly().waitFor(); - logger.trace("Force-Closing npm server in directory <{}> and port <{}> -- Finished", serverPortFile.getParent(), serverPort); + LOGGER.trace("Force-Closing npm server in directory <{}> and port <{}> -- Finished", serverPortFile.getParent(), serverPort); } } } finally { diff --git a/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java index 34f8b92857..fdf2cc4877 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java @@ -36,7 +36,7 @@ public final class PrettierFormatterStep { - private static final Logger logger = LoggerFactory.getLogger(PrettierFormatterStep.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PrettierFormatterStep.class); public static final String NAME = "prettier-format"; @@ -82,11 +82,11 @@ 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)"); + LOGGER.info("creating formatter function (starting server)"); ServerProcessInfo prettierRestServer = toRuntime().npmRunServer(); PrettierRestService restService = new PrettierRestService(prettierRestServer.getBaseUrl()); String prettierConfigOptions = restService.resolveConfig(this.prettierConfig.getPrettierConfigPath(), this.prettierConfig.getOptions()); @@ -97,11 +97,11 @@ public FormatterFunc createFormatterFunc() { } private void endServer(PrettierRestService restService, ServerProcessInfo restServer) throws Exception { - logger.info("Closing formatting function (ending server)."); + LOGGER.info("Closing formatting function (ending server)."); try { restService.shutdown(); } catch (Throwable t) { - logger.info("Failed to request shutdown of rest service via api. Trying via process.", t); + LOGGER.info("Failed to request shutdown of rest service via api. Trying via process.", t); } restServer.close(); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java b/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java index 02b5c8fb82..c1a9129d89 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java @@ -114,7 +114,7 @@ private static String guessPlugin(File file) { .filter(entry -> file.getName().endsWith(entry.getKey())) .findFirst() .map(Map.Entry::getValue) - .orElse("prettier-plugin-" + extension(file)); + .orElseGet(() -> "prettier-plugin-" + extension(file)); } public String fileType() { diff --git a/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java b/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java index 6adf3a28dd..af7d956c16 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/ShadowCopy.java @@ -40,7 +40,7 @@ class ShadowCopy { - private static final Logger logger = LoggerFactory.getLogger(ShadowCopy.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ShadowCopy.class); private final Supplier shadowCopyRootSupplier; @@ -59,13 +59,13 @@ private File shadowCopyRoot() { public void addEntry(String key, File orig) { File target = entry(key, orig.getName()); if (target.exists()) { - logger.debug("Shadow copy entry already exists, not overwriting: {}", key); + LOGGER.debug("Shadow copy entry already exists, not overwriting: {}", key); } else { try { storeEntry(key, orig, target); } catch (Throwable ex) { // Log but don't fail - logger.warn("Unable to store cache entry for {}", key, ex); + LOGGER.warn("Unable to store cache entry for {}", key, ex); } } } @@ -75,20 +75,20 @@ private void storeEntry(String key, File orig, File target) throws IOException { // Create a temp directory in the same directory as target Files.createDirectories(target.toPath().getParent()); Path tempDirectory = Files.createTempDirectory(target.toPath().getParent(), key); - logger.debug("Will store entry {} to temporary directory {}, which is a sibling of the ultimate target {}", orig, tempDirectory, target); + LOGGER.debug("Will store entry {} to temporary directory {}, which is a sibling of the ultimate target {}", orig, tempDirectory, target); try { // Copy orig to temp dir Files.walkFileTree(orig.toPath(), new CopyDirectoryRecursively(tempDirectory, orig.toPath())); try { - logger.debug("Finished storing entry {}. Atomically moving temporary directory {} into final place {}", key, tempDirectory, target); + LOGGER.debug("Finished storing entry {}. Atomically moving temporary directory {} into final place {}", key, tempDirectory, target); // Atomically rename the completed cache entry into place Files.move(tempDirectory, target.toPath(), StandardCopyOption.ATOMIC_MOVE); } catch (FileAlreadyExistsException | DirectoryNotEmptyException e) { // Someone already beat us to it - logger.debug("Shadow copy entry now exists, not overwriting: {}", key); + LOGGER.debug("Shadow copy entry now exists, not overwriting: {}", key); } catch (AtomicMoveNotSupportedException e) { - logger.warn("The filesystem at {} does not support atomic moves. Spotless cannot safely cache on such a system due to race conditions. Caching has been skipped.", target.toPath().getParent(), e); + LOGGER.warn("The filesystem at {} does not support atomic moves. Spotless cannot safely cache on such a system due to race conditions. Caching has been skipped.", target.toPath().getParent(), e); } } finally { // Best effort to clean up @@ -96,7 +96,7 @@ private void storeEntry(String key, File orig, File target) throws IOException { try { Files.walkFileTree(tempDirectory, new DeleteDirectoryRecursively()); } catch (Throwable ex) { - logger.warn("Ignoring error while cleaning up temporary copy", ex); + LOGGER.warn("Ignoring error while cleaning up temporary copy", ex); } } } @@ -113,7 +113,7 @@ private File entry(String key, String origName) { public File copyEntryInto(String key, String origName, File targetParentFolder) { File target = Path.of(targetParentFolder.getAbsolutePath(), origName).toFile(); if (target.exists()) { - logger.warn("Shadow copy destination already exists, deleting! {}: {}", key, target); + LOGGER.warn("Shadow copy destination already exists, deleting! {}: {}", key, target); ThrowingEx.run(() -> Files.walkFileTree(target.toPath(), new DeleteDirectoryRecursively())); } // copy directory "orig" to "target" using hard links if possible or a plain copy otherwise @@ -151,10 +151,10 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO Files.createLink(target.resolve(orig.relativize(file)), file); return super.visitFile(file, attrs); } catch (UnsupportedOperationException | SecurityException | FileSystemException e) { - logger.debug("Shadow copy entry does not support hard links: {}. Switching to 'copy'.", file, e); + LOGGER.debug("Shadow copy entry does not support hard links: {}. Switching to 'copy'.", file, e); tryHardLink = false; // remember that hard links are not supported } catch (IOException e) { - logger.debug("Shadow copy entry failed to create hard link: {}. Switching to 'copy'.", file, e); + LOGGER.debug("Shadow copy entry failed to create hard link: {}. Switching to 'copy'.", file, e); tryHardLink = false; // remember that hard links are not supported } } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java index 787b14c9c9..f8c79a664d 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java @@ -38,7 +38,7 @@ public final class TsFmtFormatterStep { - private static final Logger logger = LoggerFactory.getLogger(TsFmtFormatterStep.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TsFmtFormatterStep.class); public static final String NAME = "tsfmt-format"; @@ -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(); @@ -121,7 +121,7 @@ private void endServer(TsFmtRestService restService, ServerProcessInfo restServe try { restService.shutdown(); } catch (Throwable t) { - logger.info("Failed to request shutdown of rest service via api. Trying via process.", t); + LOGGER.info("Failed to request shutdown of rest service via api. Trying via process.", t); } restServer.close(); } diff --git a/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java b/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java index 51f2aff90d..061062434f 100644 --- a/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java @@ -43,7 +43,7 @@ import org.slf4j.LoggerFactory; class ReflectionHelper { - private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private final RdfFormatterStep.State state; private final ClassLoader classLoader; private final Class JenaRdfDataMgrClass; @@ -202,10 +202,10 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl long col = (long) args[2]; String severity = method.getName(); if ("warning".equals(severity) && !state.getConfig().isFailOnWarning()) { - logger.warn("{}({},{}): {}", this.filePath, line, col, message); + LOGGER.warn("{}({},{}): {}", this.filePath, line, col, message); } else { if ("warning".equals(severity)) { - logger.error("Formatter fails because of a parser warning. To make the formatter succeed in" + LOGGER.error("Formatter fails because of a parser warning. To make the formatter succeed in" + "the presence of warnings, set the configuration parameter 'failOnWarning' to 'false' (default: 'true')"); } throw new RuntimeException( diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokenizedFormatter.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokenizedFormatter.java index 53d1cae485..52665bf716 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokenizedFormatter.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokenizedFormatter.java @@ -37,7 +37,7 @@ public class SQLTokenizedFormatter { private static final String[] JOIN_BEGIN = {"LEFT", "RIGHT", "INNER", "OUTER", "JOIN"}; - private static final SQLDialect sqlDialect = SQLDialect.INSTANCE; + private static final SQLDialect SQL_DIALECT = SQLDialect.INSTANCE; private DBeaverSQLFormatterConfiguration formatterCfg; private List functionBracket = new ArrayList<>(); private List statementDelimiters = new ArrayList<>(2); @@ -251,7 +251,7 @@ private List format(final List argList) { } } else if (token.getType() == TokenType.COMMENT) { boolean isComment = false; - String[] slComments = sqlDialect.getSingleLineComments(); + String[] slComments = SQL_DIALECT.getSingleLineComments(); for (String slc : slComments) { if (token.getString().startsWith(slc)) { isComment = true; @@ -259,7 +259,7 @@ private List format(final List argList) { } } if (!isComment) { - Pair mlComments = sqlDialect.getMultiLineComments(); + Pair mlComments = SQL_DIALECT.getMultiLineComments(); if (token.getString().startsWith(mlComments.getFirst())) { index += insertReturnAndIndent(argList, index + 1, indent); } @@ -385,7 +385,7 @@ private boolean isJoinStart(List argList, int index) { } private boolean isFunction(String name) { - return sqlDialect.getKeywordType(name) == DBPKeywordType.FUNCTION; + return SQL_DIALECT.getKeywordType(name) == DBPKeywordType.FUNCTION; } private static String getDefaultLineSeparator() { @@ -406,7 +406,7 @@ private int insertReturnAndIndent(final List argList, final int final FormatterToken token = argList.get(argIndex); final FormatterToken prevToken = argList.get(argIndex - 1); if (token.getType() == TokenType.COMMENT - && isCommentLine(sqlDialect, token.getString()) + && isCommentLine(SQL_DIALECT, token.getString()) && prevToken.getType() != TokenType.END) { s.setCharAt(0, ' '); s.setLength(1); diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java index f80b084c91..3216f9990e 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java @@ -31,8 +31,8 @@ */ class SQLTokensParser { - private static final String[] twoCharacterSymbol = {"<>", "<=", ">=", "||", "()", "!=", ":=", ".*"}; - private static final SQLDialect sqlDialect = SQLDialect.INSTANCE; + private static final String[] TWO_CHARACTER_SYMBOL = {"<>", "<=", ">=", "||", "()", "!=", ":=", ".*"}; + private static final SQLDialect SQL_DIALECT = SQLDialect.INSTANCE; private final String[][] quoteStrings; private final char structSeparator; @@ -44,10 +44,10 @@ class SQLTokensParser { private int fPos; SQLTokensParser() { - this.structSeparator = sqlDialect.getStructSeparator(); - this.catalogSeparator = sqlDialect.getCatalogSeparator(); - this.quoteStrings = sqlDialect.getIdentifierQuoteStrings(); - this.singleLineComments = sqlDialect.getSingleLineComments(); + this.structSeparator = SQL_DIALECT.getStructSeparator(); + this.catalogSeparator = SQL_DIALECT.getCatalogSeparator(); + this.quoteStrings = SQL_DIALECT.getIdentifierQuoteStrings(); + this.singleLineComments = SQL_DIALECT.getSingleLineComments(); this.singleLineCommentStart = new char[this.singleLineComments.length]; for (int i = 0; i < singleLineComments.length; i++) { if (singleLineComments[i].isEmpty()) { @@ -186,9 +186,9 @@ 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) { + if (SQL_DIALECT.getKeywordType(word) != null) { return new FormatterToken(TokenType.KEYWORD, word, start_pos); } return new FormatterToken(TokenType.NAME, word, start_pos); @@ -250,7 +250,7 @@ else if (isSymbol(fChar)) { return new FormatterToken(TokenType.SYMBOL, s.toString(), start_pos); } char ch2 = fBefore.charAt(fPos); - for (String aTwoCharacterSymbol : twoCharacterSymbol) { + for (String aTwoCharacterSymbol : TWO_CHARACTER_SYMBOL) { if (aTwoCharacterSymbol.charAt(0) == fChar && aTwoCharacterSymbol.charAt(1) == ch2) { fPos++; s.append(ch2); diff --git a/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java b/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java index 53a186169f..bee6b9c70a 100644 --- a/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java +++ b/lib/src/sortPom/java/com/diffplug/spotless/glue/pom/SortPomFormatterFunc.java @@ -33,7 +33,7 @@ import sortpom.parameter.PluginParameters; public class SortPomFormatterFunc implements FormatterFunc { - private static final Logger logger = LoggerFactory.getLogger(SortPomFormatterFunc.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SortPomFormatterFunc.class); private final SortPomCfg cfg; public SortPomFormatterFunc(SortPomCfg cfg) { @@ -101,19 +101,19 @@ public MySortPomLogger(boolean quiet) { @Override public void warn(String content) { - logger.warn(content); + LOGGER.warn(content); } @Override public void info(String content) { if (!quiet) { - logger.info(content); + LOGGER.info(content); } } @Override public void error(String content) { - logger.error(content); + LOGGER.error(content); } } } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FormatExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FormatExtension.java index 777223c5f7..4011bf6d6c 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FormatExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FormatExtension.java @@ -83,7 +83,7 @@ /** Adds a {@code spotless{Name}Check} and {@code spotless{Name}Apply} task. */ public class FormatExtension { - private static final Logger logger = LoggerFactory.getLogger(FormatExtension.class); + private static final Logger LOGGER = LoggerFactory.getLogger(FormatExtension.class); final SpotlessExtension spotless; final List> lazyActions = new ArrayList<>(); @@ -548,7 +548,7 @@ public void indentWithTabs() { } private static void logDeprecation(String methodName, String replacement) { - logger.warn("'{}' is deprecated, use '{}' in your gradle build script instead.", methodName, replacement); + LOGGER.warn("'{}' is deprecated, use '{}' in your gradle build script instead.", methodName, replacement); } /** Ensures formatting of files via native binary. */ diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/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/GradleProvisioner.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GradleProvisioner.java index d6b6369bf8..b8260e3b9c 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GradleProvisioner.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GradleProvisioner.java @@ -142,7 +142,7 @@ private static Provisioner forConfigurationContainer(Project project, Configurat }; } - private static final Logger logger = LoggerFactory.getLogger(GradleProvisioner.class); + private static final Logger LOGGER = LoggerFactory.getLogger(GradleProvisioner.class); /** Models a request to the provisioner. */ private static class Request { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java index 33aded8bdd..c1f8e10ba3 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. @@ -21,8 +21,6 @@ import java.util.ArrayList; import java.util.List; -import javax.inject.Inject; - import org.gradle.api.DefaultTask; import org.gradle.api.provider.Provider; import org.gradle.api.services.BuildServiceRegistry; @@ -99,6 +97,5 @@ public Provider getTaskService() { return taskService; } - @Inject protected abstract BuildEventsListenerRegistry getBuildEventsListenerRegistry(); } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.java index c623669ab1..39a3f4a9b2 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.java @@ -48,7 +48,7 @@ public void visitFile(FileVisitDetails fileVisitDetails) { String path = fileVisitDetails.getPath(); File originalSource = new File(getProjectDir().get().getAsFile(), path); try { - getLogger().debug("Copying " + fileVisitDetails.getFile() + " to " + originalSource); + getLogger().debug("Copying {} to {}", fileVisitDetails.getFile(), originalSource); Files.copy(fileVisitDetails.getFile().toPath(), originalSource.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); } catch (IOException e) { throw new RuntimeException(e); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessDiagnoseTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessDiagnoseTask.java index a029bd00d4..d73b56d93b 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() @@ -49,7 +49,7 @@ public void performAction() throws IOException { getProject().delete(diagnoseRoot.toFile()); try (Formatter formatter = source.buildFormatter()) { for (File file : source.target) { - getLogger().debug("Running padded cell check on " + file); + getLogger().debug("Running padded cell check on {}", file); PaddedCell padded = PaddedCell.check(formatter, file); if (!padded.misbehaved()) { getLogger().debug(" well-behaved."); 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..53e51dcbde 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 @@ -137,9 +137,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/SpotlessTaskImpl.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskImpl.java index 252e418a0b..37148a7123 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskImpl.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskImpl.java @@ -24,7 +24,6 @@ import java.util.List; import javax.annotation.Nullable; -import javax.inject.Inject; import org.gradle.api.GradleException; import org.gradle.api.file.DirectoryProperty; @@ -73,7 +72,6 @@ Provider getTaskServiceProvider() { return taskServiceProvider; } - @Inject protected abstract FileSystemOperations getFs(); @TaskAction @@ -152,7 +150,7 @@ void processInputFile(@Nullable GitRatchet ratchet, Formatter formatter, File in // Need to copy the original file to the tmp location just to remember the file attributes Files.copy(input.toPath(), cleanFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); - getLogger().info("Writing clean file: %s".formatted(cleanFile)); + getLogger().info("Writing clean file: {}", cleanFile); lintState.getDirtyState().writeCanonicalTo(cleanFile); } if (!lintState.isHasLints()) { 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..f7285abf94 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 @@ -25,7 +25,6 @@ import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; -import javax.inject.Inject; import org.gradle.api.DefaultTask; import org.gradle.api.file.ConfigurableFileTree; @@ -122,7 +121,6 @@ abstract static class ClientTask extends DefaultTask { @Internal abstract DirectoryProperty getProjectDir(); - @Inject protected abstract ObjectFactory getConfigCacheWorkaround(); void init(SpotlessTaskImpl impl) { @@ -178,7 +176,7 @@ public void visitDir(FileVisitDetails fileVisitDetails) { @Override public void visitFile(FileVisitDetails fileVisitDetails) { String path = fileVisitDetails.getPath(); - getLogger().debug("Reading lints for " + path); + getLogger().debug("Reading lints for {}", path); LinkedHashMap> lints = SerializableMisc.fromFile(LinkedHashMap.class, fileVisitDetails.getFile()); allLints.put(path, lints); lints.values().forEach(list -> total.addAndGet(list.size())); 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..a1807ec4eb 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. @@ -31,7 +31,7 @@ import com.diffplug.spotless.maven.FormatterStepFactory; public class Ktlint implements FormatterStepFactory { - private static final File defaultEditorConfig = new File(".editorconfig"); + private static final File DEFAULT_EDITOR_CONFIG = new File(".editorconfig"); @Parameter private String version; @@ -46,8 +46,8 @@ public class Ktlint implements FormatterStepFactory { public FormatterStep newFormatterStep(final FormatterStepConfig stepConfig) { String ktlintVersion = version != null ? version : KtLintStep.defaultVersion(); FileSignature configPath = null; - if (editorConfigPath == null && defaultEditorConfig.exists()) { - editorConfigPath = defaultEditorConfig.getPath(); + if (editorConfigPath == null && DEFAULT_EDITOR_CONFIG.exists()) { + editorConfigPath = DEFAULT_EDITOR_CONFIG.getPath(); } if (editorConfigPath != null) { configPath = ThrowingEx.get(() -> FileSignature.signAsList(stepConfig.getFileLocator().locateFile(editorConfigPath))); diff --git a/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/TestProvisioner.java b/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java index 672dd8eba9..c75d618ac0 100644 --- a/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java +++ b/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java @@ -140,22 +140,22 @@ private static Provisioner caching(String name, Supplier input) { /** Creates a Provisioner for the mavenCentral repo. */ public static Provisioner mavenCentral() { - return mavenCentral.get(); + return MAVEN_CENTRAL.get(); } - private static final Supplier mavenCentral = Suppliers.memoize(() -> caching("mavenCentral", () -> createWithRepositories(repo -> repo.mavenCentral()))); + private static final Supplier MAVEN_CENTRAL = Suppliers.memoize(() -> caching("mavenCentral", () -> createWithRepositories(repo -> repo.mavenCentral()))); /** Creates a Provisioner for the local maven repo for development purpose. */ public static Provisioner mavenLocal() { - return mavenLocal.get(); + return MAVEN_LOCAL.get(); } - private static final Supplier mavenLocal = () -> createWithRepositories(repo -> repo.mavenLocal()); + private static final Supplier MAVEN_LOCAL = () -> createWithRepositories(repo -> repo.mavenLocal()); /** Creates a Provisioner for the Sonatype snapshots maven repo for development purpose. */ public static Provisioner snapshots() { - return snapshots.get(); + return SNAPSHOTS.get(); } - private static final Supplier snapshots = () -> createWithRepositories(repo -> repo.maven(setup -> setup.setUrl("https://oss.sonatype.org/content/repositories/snapshots"))); + private static final Supplier SNAPSHOTS = () -> createWithRepositories(repo -> repo.maven(setup -> setup.setUrl("https://oss.sonatype.org/content/repositories/snapshots"))); } diff --git a/testlib/src/main/java/com/diffplug/spotless/npm/EslintStyleGuide.java b/testlib/src/main/java/com/diffplug/spotless/npm/EslintStyleGuide.java index 4e1d168a2a..81157a7411 100644 --- a/testlib/src/main/java/com/diffplug/spotless/npm/EslintStyleGuide.java +++ b/testlib/src/main/java/com/diffplug/spotless/npm/EslintStyleGuide.java @@ -26,8 +26,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 +39,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 +48,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 +57,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 +76,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; 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 {}