diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 6e7dbc6435..9603cdc553 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -5,16 +5,23 @@ on: types: [created] pull_request_review_comment: types: [created] - issues: - types: [opened, assigned] pull_request_review: types: [submitted] + issues: + types: [opened, assigned] jobs: - check-team-membership: + claude: + # Only run if @claude is mentioned in the triggering content + # For issues (opened/assigned), checks the issue body or title + # For comments/reviews, checks the comment/review body + if: contains(github.event.comment.body || github.event.review.body || github.event.issue.body || github.event.issue.title || '', '@claude') runs-on: ubuntu-latest - outputs: - is-team-member: ${{ steps.check-membership.outputs.is-member }} + permissions: + contents: read + pull-requests: read + issues: read + id-token: write steps: - name: Check team membership id: check-membership @@ -22,57 +29,38 @@ jobs: with: script: | try { - // Get username - prioritize sender (the person who triggered the event) - const username = github.event?.sender?.login || - github.event?.comment?.user?.login; - + // Get the user who triggered the event + const username = context.payload.sender?.login; + if (!username) { - console.log('Could not determine username from event payload'); - console.log(`Event type: ${github.event_name}`); - console.log(`Event payload keys: ${Object.keys(github.event).join(', ')}`); - return false; + core.setFailed('Could not determine username from event'); + return; } - - console.log(`Checking team membership for user: ${username} (triggered by ${github.event_name} event)`); - + + console.log(`Checking if ${username} is a member of diffplug/spotless`); + const { data } = await github.rest.teams.getMembershipForUserInOrg({ org: 'diffplug', team_slug: 'spotless', username: username }); - console.log(`User ${username} membership status: ${data.state}`); - return data.state === 'active'; + + if (data.state !== 'active') { + core.setFailed(`User ${username} is not an active team member`); + } else { + console.log(`✓ ${username} is an active team member`); + } } catch (error) { - const username = github.event.sender?.login || github.event.comment?.user?.login || 'unknown user'; - console.log(`User ${username} is not a member of the Spotless team or error occurred: ${error.message}`); - return false; + // User is not a team member or API error + core.setFailed(`Access denied: ${error.message}`); } - claude: - needs: check-team-membership - if: | - needs.check-team-membership.outputs.is-team-member == 'true' && - ( - (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) || - (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) || - (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) || - (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude'))) - ) - runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: read - issues: read - id-token: write - steps: - name: Checkout repository uses: actions/checkout@v5 with: fetch-depth: 1 - name: Run Claude Code - id: claude uses: anthropics/claude-code-action@beta with: - anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} - + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} \ No newline at end of file diff --git a/gradle/rewrite.gradle b/gradle/rewrite.gradle index 04d554371d..9f75f75e96 100644 --- a/gradle/rewrite.gradle +++ b/gradle/rewrite.gradle @@ -1,46 +1,10 @@ apply plugin: 'org.openrewrite.rewrite' rewrite { - activeRecipe( - 'org.openrewrite.gradle.GradleBestPractices', - 'org.openrewrite.java.RemoveUnusedImports', - 'org.openrewrite.java.format.RemoveTrailingWhitespace', - 'org.openrewrite.java.migrate.UpgradeToJava17', - 'org.openrewrite.java.recipes.JavaRecipeBestPractices', - 'org.openrewrite.java.recipes.RecipeTestingBestPractices', - 'org.openrewrite.java.security.JavaSecurityBestPractices', - 'org.openrewrite.staticanalysis.EqualsAvoidsNull', - 'org.openrewrite.staticanalysis.JavaApiBestPractices', - 'org.openrewrite.staticanalysis.LowercasePackage', - 'org.openrewrite.staticanalysis.MissingOverrideAnnotation', - 'org.openrewrite.staticanalysis.ModifierOrder', - 'org.openrewrite.staticanalysis.NoFinalizer', - 'org.openrewrite.staticanalysis.NoToStringOnStringType', - 'org.openrewrite.staticanalysis.NoValueOfOnStringType', - 'org.openrewrite.staticanalysis.RemoveUnusedLocalVariables', - 'org.openrewrite.staticanalysis.RemoveUnusedPrivateFields', - 'org.openrewrite.staticanalysis.RemoveUnusedPrivateMethods', - 'org.openrewrite.staticanalysis.UnnecessaryCloseInTryWithResources', - 'org.openrewrite.staticanalysis.UnnecessaryExplicitTypeArguments', - 'org.openrewrite.staticanalysis.UnnecessaryParentheses', - 'org.openrewrite.staticanalysis.UnnecessaryReturnAsLastStatement', - 'tech.picnic.errorprone.refasterrules.BigDecimalRulesRecipes', - 'tech.picnic.errorprone.refasterrules.CharSequenceRulesRecipes', - 'tech.picnic.errorprone.refasterrules.ClassRulesRecipes', - 'tech.picnic.errorprone.refasterrules.CollectionRulesRecipes', - 'tech.picnic.errorprone.refasterrules.ComparatorRulesRecipes', - 'tech.picnic.errorprone.refasterrules.FileRulesRecipes', - 'tech.picnic.errorprone.refasterrules.MicrometerRulesRecipes', - 'tech.picnic.errorprone.refasterrules.PatternRulesRecipes', - 'tech.picnic.errorprone.refasterrules.PreconditionsRulesRecipes', - 'tech.picnic.errorprone.refasterrules.PrimitiveRulesRecipes', - 'tech.picnic.errorprone.refasterrules.StreamRulesRecipes', - 'tech.picnic.errorprone.refasterrules.TimeRulesRecipes' - //'org.openrewrite.staticanalysis.CodeCleanup', bug - //'org.openrewrite.staticanalysis.CommonStaticAnalysis', bug - //'org.openrewrite.staticanalysis.UnnecessaryThrows', bug - ) + activeRecipe('com.diffplug.spotless.openrewrite.SanityCheck') exclusions.addAll( + '**.dirty.java', + '**FormatterProperties.java', '**_gradle_node_plugin_example_**', '**gradle/changelog.gradle', '**gradle/java-publish.gradle', @@ -50,7 +14,9 @@ rewrite { '**lib/build.gradle', '**package-info.java', '**plugin-maven/build.gradle', - '**settings.gradle' + '**settings.gradle', + '**special-tests.gradle', + '**testlib/src/main/resources**' ) exportDatatables = true failOnDryRunResults = true diff --git a/lib-extra/src/groovy/java/com/diffplug/spotless/extra/glue/groovy/GrEclipseFormatterStepImpl.java b/lib-extra/src/groovy/java/com/diffplug/spotless/extra/glue/groovy/GrEclipseFormatterStepImpl.java index 163816c1a4..682e9bddbb 100644 --- a/lib-extra/src/groovy/java/com/diffplug/spotless/extra/glue/groovy/GrEclipseFormatterStepImpl.java +++ b/lib-extra/src/groovy/java/com/diffplug/spotless/extra/glue/groovy/GrEclipseFormatterStepImpl.java @@ -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. @@ -130,7 +130,7 @@ public boolean errorsDetected() { synchronized (GroovyLogManager.manager) { GroovyLogManager.manager.removeLogger(this); } - return 0 != errors.size(); + return !errors.isEmpty(); } @Override @@ -138,7 +138,7 @@ public String toString() { StringBuilder string = new StringBuilder(); if (1 < errors.size()) { string.append("Multiple problems detected during step execution:"); - } else if (0 == errors.size()) { + } else if (errors.isEmpty()) { string.append("Step sucesfully executed."); } for (Throwable error : errors) { diff --git a/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/DefaultJavaElementComparator.java b/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/DefaultJavaElementComparator.java index 6611827dc2..6c1a576d58 100644 --- a/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/DefaultJavaElementComparator.java +++ b/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/DefaultJavaElementComparator.java @@ -164,23 +164,26 @@ private int category(BodyDeclaration bodyDeclaration) { return CONSTRUCTORS_INDEX; } int flags = method.getModifiers(); - if (Modifier.isStatic(flags)) + if (Modifier.isStatic(flags)) { return STATIC_METHODS_INDEX; - else + } else { return METHOD_INDEX; + } } case ASTNode.FIELD_DECLARATION: { - if (JdtFlags.isStatic(bodyDeclaration)) + if (JdtFlags.isStatic(bodyDeclaration)) { return STATIC_FIELDS_INDEX; - else + } else { return FIELDS_INDEX; + } } case ASTNode.INITIALIZER: { int flags = bodyDeclaration.getModifiers(); - if (Modifier.isStatic(flags)) + if (Modifier.isStatic(flags)) { return STATIC_INIT_INDEX; - else + } else { return INIT_INDEX; + } } case ASTNode.TYPE_DECLARATION: case ASTNode.ENUM_DECLARATION: 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 05498b1caf..5c75a62344 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 @@ -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. @@ -33,7 +33,7 @@ import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.internal.core.SortElementsOperation; -public class EclipseJdtSortMembers { +public final class EclipseJdtSortMembers { private static final Pattern PATTERN_DO_NOT_SORT_FIELDS = Pattern.compile("@SortMembers:doNotSortFields\\s*=\\s*(false|true)"); private static final Pattern PATTERN_ENABLED = Pattern.compile("@SortMembers:enabled\\s*=\\s*(false|true)"); @@ -244,4 +244,6 @@ static SortProperties from(Map properties) { return new SortProperties(enabled, membersOrder, doNotSortFields, sortByVisibility, visibilityOrder); } } + + private EclipseJdtSortMembers() {} } diff --git a/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/JdtFlags.java b/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/JdtFlags.java index 7dfb99776b..3ddcbeb5a0 100644 --- a/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/JdtFlags.java +++ b/lib-extra/src/jdt/java/com/diffplug/spotless/extra/glue/jdt/JdtFlags.java @@ -28,22 +28,26 @@ /** * This class is derived and adapted code from the Eclipse JDT project (Derivative Works according to EPL 2.0 license). */ -class JdtFlags { +final class JdtFlags { static final int VISIBILITY_CODE_INVALID = -1; static boolean isStatic(BodyDeclaration bodyDeclaration) { - if (isNestedInterfaceOrAnnotation(bodyDeclaration)) + if (isNestedInterfaceOrAnnotation(bodyDeclaration)) { return true; + } int nodeType = bodyDeclaration.getNodeType(); if (nodeType != ASTNode.METHOD_DECLARATION && nodeType != ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION - && isInterfaceOrAnnotationMember(bodyDeclaration)) + && isInterfaceOrAnnotationMember(bodyDeclaration)) { return true; - if (bodyDeclaration instanceof EnumConstantDeclaration) + } + if (bodyDeclaration instanceof EnumConstantDeclaration) { return true; - if (bodyDeclaration instanceof EnumDeclaration && bodyDeclaration.getParent() instanceof AbstractTypeDeclaration) + } + if (bodyDeclaration instanceof EnumDeclaration && bodyDeclaration.getParent() instanceof AbstractTypeDeclaration) { return true; + } return Modifier.isStatic(bodyDeclaration.getModifiers()); } @@ -60,8 +64,9 @@ private static boolean isProtected(BodyDeclaration bodyDeclaration) { } private static boolean isPublic(BodyDeclaration bodyDeclaration) { - if (isInterfaceOrAnnotationMember(bodyDeclaration)) + if (isInterfaceOrAnnotationMember(bodyDeclaration)) { return true; + } return Modifier.isPublic(bodyDeclaration.getModifiers()); } @@ -80,15 +85,18 @@ private static boolean isNestedInterfaceOrAnnotation(BodyDeclaration bodyDeclara } static int getVisibilityCode(BodyDeclaration bodyDeclaration) { - if (isPublic(bodyDeclaration)) + if (isPublic(bodyDeclaration)) { return Modifier.PUBLIC; - else if (isProtected(bodyDeclaration)) + } else if (isProtected(bodyDeclaration)) { return Modifier.PROTECTED; - else if (isPackageVisible(bodyDeclaration)) + } else if (isPackageVisible(bodyDeclaration)) { return Modifier.NONE; - else if (isPrivate(bodyDeclaration)) + } else if (isPrivate(bodyDeclaration)) { return Modifier.PRIVATE; + } Assert.isTrue(false); return VISIBILITY_CODE_INVALID; } + + private JdtFlags() {} } diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/EclipseBasedStepBuilder.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/EclipseBasedStepBuilder.java index 01f78aab23..2c3d1a5a6c 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/EclipseBasedStepBuilder.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/EclipseBasedStepBuilder.java @@ -78,9 +78,7 @@ public EclipseBasedStepBuilder(String formatterName, String formatterStepExt, Pr /** Returns the FormatterStep (whose state will be calculated lazily). */ public FormatterStep build() { - var roundtrippableState = new EclipseStep(formatterVersion, formatterStepExt, FileSignature.promise(settingsFiles), JarState.promise(() -> { - return JarState.withoutTransitives(dependencies, jarProvisioner); - })); + var roundtrippableState = new EclipseStep(formatterVersion, formatterStepExt, FileSignature.promise(settingsFiles), JarState.promise(() -> JarState.withoutTransitives(dependencies, jarProvisioner))); return FormatterStep.create(formatterName + formatterStepExt, roundtrippableState, EclipseStep::state, stateToFormatter); } diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/EquoBasedStepBuilder.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/EquoBasedStepBuilder.java index 55b3474a03..ab813ec324 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/EquoBasedStepBuilder.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/EquoBasedStepBuilder.java @@ -61,7 +61,7 @@ public abstract class EquoBasedStepBuilder { private File cacheDirectory; /** Initialize valid default configuration, taking latest version */ - public EquoBasedStepBuilder( + protected EquoBasedStepBuilder( String formatterName, Provisioner mavenProvisioner, @Nullable String defaultVersion, diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java index 9d6491f281..af027ad42d 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java @@ -177,13 +177,15 @@ public String endingFor(File file) { static class RuntimeInit { /** /etc/gitconfig (system-global), ~/.gitconfig (each might-not exist). */ - final FileBasedConfig systemConfig, userConfig; + final FileBasedConfig systemConfig; + final FileBasedConfig userConfig; /** Repository specific config, can be $GIT_COMMON_DIR/config, project/.git/config or .git/worktrees//config.worktree if enabled by extension */ final Config repoConfig; /** Global .gitattributes file pointed at by systemConfig or userConfig, and the file in the repo. */ - final @Nullable File globalAttributesFile, repoAttributesFile; + final @Nullable File globalAttributesFile; + final @Nullable File repoAttributesFile; /** git worktree root, might not exist if we're not in a git repo. */ final @Nullable File workTree; @@ -235,7 +237,7 @@ private Runtime atRuntime() { } /** https://github.com/git/git/blob/1fe8f2cf461179c41f64efbd1dc0a9fb3b7a0fb1/Documentation/gitattributes.txt */ - static class Runtime { + static final class Runtime { /** .git/info/attributes (and the worktree with that file) */ final List infoRules; diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitRatchet.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitRatchet.java index c8f5fb68fb..f30e8fd002 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitRatchet.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitRatchet.java @@ -62,7 +62,7 @@ public boolean isClean(Project project, ObjectId treeSha, File file) throws IOEx return isClean(project, treeSha, relativePath); } - private Map dirCaches = new HashMap<>(); + private final Map dirCaches = new HashMap<>(); /** * This is the highest-level method, which all the others serve. Given the sha 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 94065f0059..97c95615fb 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitWorkarounds.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitWorkarounds.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2023 DiffPlug + * Copyright 2020-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -202,7 +202,7 @@ private static IOException emptyFile(File commonDir) { return new IOException("Empty 'commondir' file: " + commonDir.getAbsolutePath()); } - @SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE") + @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE") @Override public FileRepositoryBuilder readEnvironment(SystemReader sr) { super.readEnvironment(sr); diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStep.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStep.java index 7cae8c942b..e73ef6e2ab 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStep.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStep.java @@ -66,9 +66,7 @@ protected P2Model model(String version) { "org.codehaus.groovy.eclipse.core", "org.eclipse.jdt.groovy.core", "org.codehaus.groovy")); - model.addFilterAndValidate("no-debug", filter -> { - filter.exclude("org.eclipse.jdt.debug"); - }); + model.addFilterAndValidate("no-debug", filter -> filter.exclude("org.eclipse.jdt.debug")); // work around https://github.com/groovy/groovy-eclipse/issues/1617 model.useMavenCentral = false; return model; diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/integration/DiffMessageFormatter.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/integration/DiffMessageFormatter.java index 2b05bf93c3..fb9d176eac 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/integration/DiffMessageFormatter.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/integration/DiffMessageFormatter.java @@ -112,7 +112,7 @@ public String getFormatted(File file, String rawUnix) { } } - public static class Builder { + public static final class Builder { private Builder() {} private String runToFix; @@ -161,7 +161,7 @@ public String getMessage() { public static final int MAX_FILES_TO_LIST = 10; private final StringBuilder buffer = new StringBuilder(MAX_CHECK_MESSAGE_LINES * 64); - private int numLines = 0; + private int numLines; private final CleanProvider formatter; @@ -203,7 +203,7 @@ private void addFile(String arg) { if (!lines.isEmpty()) { addIntendedLine(NORMAL_INDENT, lines.get(0)); } - for (int i = 1; i < Math.min(MIN_LINES_PER_FILE, lines.size()); ++i) { + for (int i = 1; i < Math.min(MIN_LINES_PER_FILE, lines.size()); i++) { addIntendedLine(DIFF_INDENT, lines.get(i)); } diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStep.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStep.java index d2afcf9ac2..dc339d9930 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStep.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStep.java @@ -29,11 +29,11 @@ /** Formatter step which calls out to the Groovy-Eclipse formatter. */ public enum EclipseWtpFormatterStep { // @formatter:off - CSS ("EclipseCssFormatterStepImpl", EclipseWtpFormatterStep::applyWithoutFile), + CSS("EclipseCssFormatterStepImpl", EclipseWtpFormatterStep::applyWithoutFile), HTML("EclipseHtmlFormatterStepImpl", EclipseWtpFormatterStep::applyWithoutFile), - JS ("EclipseJsFormatterStepImpl", EclipseWtpFormatterStep::applyWithoutFile), + JS("EclipseJsFormatterStepImpl", EclipseWtpFormatterStep::applyWithoutFile), JSON("EclipseJsonFormatterStepImpl", EclipseWtpFormatterStep::applyWithoutFile), - XML ("EclipseXmlFormatterStepImpl", EclipseWtpFormatterStep::applyWithFile); + XML("EclipseXmlFormatterStepImpl", EclipseWtpFormatterStep::applyWithFile); // @formatter:on private static final String NAME = "eclipse wtp formatter"; diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/GitRachetMergeBaseTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/GitRachetMergeBaseTest.java index 7f2ad99b54..dabc6afeb0 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/GitRachetMergeBaseTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/GitRachetMergeBaseTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2024 DiffPlug + * Copyright 2020-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -111,7 +111,7 @@ public void onlyDirty(String... filenames) throws IOException { continue; } boolean expectedClean = !dirtyFiles.contains(file.getName()); - for (int i = 0; i < shas.length; ++i) { + for (int i = 0; i < shas.length; i++) { assertClean(i, file.getName(), expectedClean); } } diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/eclipse/EclipseResourceHarness.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/eclipse/EclipseResourceHarness.java index cd4bebd390..7bf35667a1 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/eclipse/EclipseResourceHarness.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/eclipse/EclipseResourceHarness.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,6 @@ */ package com.diffplug.spotless.extra.eclipse; -import static org.assertj.core.api.Assertions.*; - import java.io.File; import java.util.Arrays; diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepSpecialCaseTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepSpecialCaseTest.java index e5159a4498..25eeb9808c 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepSpecialCaseTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStepSpecialCaseTest.java @@ -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. @@ -30,10 +30,8 @@ public class GrEclipseFormatterStepSpecialCaseTest { */ @Test public void issue_1657() { - Assertions.assertThrows(RuntimeException.class, () -> { - StepHarness.forStep(GrEclipseFormatterStep.createBuilder(TestProvisioner.mavenCentral()).build()) - .testResourceUnaffected("groovy/greclipse/format/SomeClass.test"); - }); + Assertions.assertThrows(RuntimeException.class, () -> StepHarness.forStep(GrEclipseFormatterStep.createBuilder(TestProvisioner.mavenCentral()).build()) + .testResourceUnaffected("groovy/greclipse/format/SomeClass.test")); } @Test diff --git a/lib-extra/src/test/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStepTest.java b/lib-extra/src/test/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStepTest.java index 2500e611c1..ea0001d517 100644 --- a/lib-extra/src/test/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStepTest.java +++ b/lib-extra/src/test/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStepTest.java @@ -37,7 +37,8 @@ public class EclipseWtpFormatterStepTest { private static final Jvm.Support JVM_SUPPORT = Jvm. support("Oldest Version").add(8, "4.8.0"); private static class NestedTests extends EclipseResourceHarness { - private final String unformatted, formatted; + private final String unformatted; + private final String formatted; public NestedTests(String unformatted, String formatted, EclipseWtpFormatterStep kind) { super(kind.createBuilder(TestProvisioner.mavenCentral())); diff --git a/lib/src/jackson/java/com/diffplug/spotless/glue/json/AJacksonFormatterFunc.java b/lib/src/jackson/java/com/diffplug/spotless/glue/json/AJacksonFormatterFunc.java index 1f317fa3b4..a617eb0239 100644 --- a/lib/src/jackson/java/com/diffplug/spotless/glue/json/AJacksonFormatterFunc.java +++ b/lib/src/jackson/java/com/diffplug/spotless/glue/json/AJacksonFormatterFunc.java @@ -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. @@ -32,9 +32,9 @@ */ // https://github.com/FasterXML/jackson-dataformats-text/issues/372 public abstract class AJacksonFormatterFunc implements FormatterFunc { - private JacksonConfig jacksonConfig; + private final JacksonConfig jacksonConfig; - public AJacksonFormatterFunc(JacksonConfig jacksonConfig) { + protected AJacksonFormatterFunc(JacksonConfig jacksonConfig) { this.jacksonConfig = jacksonConfig; } @@ -49,9 +49,7 @@ protected String format(ObjectMapper objectMapper, String input) throws IllegalA try { // ObjectNode is not compatible with SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS Object objectNode = objectMapper.readValue(input, inferType(input)); - String output = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectNode); - - return output; + return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectNode); } catch (JsonProcessingException e) { throw new IllegalArgumentException("Unable to format. input='" + input + "'", e); } diff --git a/lib/src/jackson/java/com/diffplug/spotless/glue/json/JacksonJsonFormatterFunc.java b/lib/src/jackson/java/com/diffplug/spotless/glue/json/JacksonJsonFormatterFunc.java index 57c8e9aedf..bfb73b755c 100644 --- a/lib/src/jackson/java/com/diffplug/spotless/glue/json/JacksonJsonFormatterFunc.java +++ b/lib/src/jackson/java/com/diffplug/spotless/glue/json/JacksonJsonFormatterFunc.java @@ -32,7 +32,7 @@ */ // https://github.com/FasterXML/jackson-dataformats-text/issues/372 public class JacksonJsonFormatterFunc extends AJacksonFormatterFunc { - private JacksonJsonConfig jacksonConfig; + private final JacksonJsonConfig jacksonConfig; public JacksonJsonFormatterFunc(JacksonJsonConfig jacksonConfig) { super(jacksonConfig); diff --git a/lib/src/ktlint/java/com/diffplug/spotless/glue/ktlint/KtlintFormatterFunc.java b/lib/src/ktlint/java/com/diffplug/spotless/glue/ktlint/KtlintFormatterFunc.java index a572d3a577..78a2e481c8 100644 --- a/lib/src/ktlint/java/com/diffplug/spotless/glue/ktlint/KtlintFormatterFunc.java +++ b/lib/src/ktlint/java/com/diffplug/spotless/glue/ktlint/KtlintFormatterFunc.java @@ -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. @@ -22,7 +22,12 @@ import com.diffplug.spotless.FileSignature; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.Lint; -import com.diffplug.spotless.glue.ktlint.compat.*; +import com.diffplug.spotless.glue.ktlint.compat.KtLintCompat0Dot48Dot0Adapter; +import com.diffplug.spotless.glue.ktlint.compat.KtLintCompat0Dot49Dot0Adapter; +import com.diffplug.spotless.glue.ktlint.compat.KtLintCompat0Dot50Dot0Adapter; +import com.diffplug.spotless.glue.ktlint.compat.KtLintCompat1Dot0Dot0Adapter; +import com.diffplug.spotless.glue.ktlint.compat.KtLintCompatAdapter; +import com.diffplug.spotless.glue.ktlint.compat.KtLintCompatReporting; public class KtlintFormatterFunc implements FormatterFunc.NeedsFile { private final KtLintCompatAdapter adapter; diff --git a/lib/src/main/java/com/diffplug/spotless/ConfigurationCacheHackList.java b/lib/src/main/java/com/diffplug/spotless/ConfigurationCacheHackList.java index a009c2e51e..7ae51024f2 100644 --- a/lib/src/main/java/com/diffplug/spotless/ConfigurationCacheHackList.java +++ b/lib/src/main/java/com/diffplug/spotless/ConfigurationCacheHackList.java @@ -16,6 +16,8 @@ package com.diffplug.spotless; import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.io.Serial; import java.io.Serializable; import java.util.ArrayList; @@ -51,7 +53,7 @@ * It is a horrific hack, but it works, and it's the only way I can figure * to make Spotless work with all of Gradle's cache systems at once. */ -public class ConfigurationCacheHackList implements java.io.Serializable { +public final class ConfigurationCacheHackList implements Serializable { @Serial private static final long serialVersionUID = 6914178791997323870L; @@ -59,10 +61,10 @@ public class ConfigurationCacheHackList implements java.io.Serializable { private ArrayList backingList = new ArrayList<>(); private boolean shouldWeSerializeToByteArrayFirst() { - return backingList.stream().anyMatch(step -> step instanceof SerializeToByteArrayHack); + return backingList.stream().anyMatch(SerializeToByteArrayHack.class::isInstance); } - private void writeObject(java.io.ObjectOutputStream out) throws IOException { + private void writeObject(ObjectOutputStream out) throws IOException { boolean serializeToByteArrayFirst = shouldWeSerializeToByteArrayFirst(); out.writeBoolean(serializeToByteArrayFirst); out.writeBoolean(optimizeForEquality); @@ -78,7 +80,7 @@ private void writeObject(java.io.ObjectOutputStream out) throws IOException { } } - private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { boolean serializeToByteArrayFirst = in.readBoolean(); optimizeForEquality = in.readBoolean(); backingList = new ArrayList<>(); @@ -133,13 +135,15 @@ public List getSteps() { @Override public boolean equals(Object o) { - if (this == o) + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } ConfigurationCacheHackList stepList = (ConfigurationCacheHackList) o; - return optimizeForEquality == stepList.optimizeForEquality && - backingList.equals(stepList.backingList); + return optimizeForEquality == stepList.optimizeForEquality + && backingList.equals(stepList.backingList); } @Override diff --git a/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java b/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java index 3e4bb3423b..a7d5e1e478 100644 --- a/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java +++ b/lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,9 +29,9 @@ import javax.annotation.Nullable; -class EncodingErrorMsg { +final class EncodingErrorMsg { static final char UNREPRESENTABLE = '�'; - private static int CONTEXT = 3; + private static final int CONTEXT = 3; static @Nullable String msg(String chars, byte[] bytes, Charset charset) { int unrepresentable = chars.indexOf(UNREPRESENTABLE); @@ -70,12 +70,12 @@ private EncodingErrorMsg(String chars, ByteBuffer byteBuf, Charset charset, int if (charset.equals(StandardCharsets.UTF_8)) { message.append("Spotless uses UTF-8 by default."); } else { - message.append("You configured Spotless to use " + charset.name() + "."); + message.append("You configured Spotless to use ").append(charset.name()).append("."); } int line = 1; int col = 1; - for (int i = 0; i < unrepresentable; ++i) { + for (int i = 0; i < unrepresentable; i++) { char c = chars.charAt(i); if (c == '\n') { ++line; @@ -84,7 +84,7 @@ private EncodingErrorMsg(String chars, ByteBuffer byteBuf, Charset charset, int ++col; } } - message.append(" At line " + line + " col " + col + ":"); + message.append(" At line ").append(line).append(" col ").append(col).append(":"); // https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html LinkedHashSet encodings = new LinkedHashSet<>(); diff --git a/lib/src/main/java/com/diffplug/spotless/FileSignature.java b/lib/src/main/java/com/diffplug/spotless/FileSignature.java index 9a2ea1c1d8..f0332aef1f 100644 --- a/lib/src/main/java/com/diffplug/spotless/FileSignature.java +++ b/lib/src/main/java/com/diffplug/spotless/FileSignature.java @@ -76,7 +76,7 @@ public static FileSignature signAsSet(Iterable files) throws IOException { StringBuilder builder = new StringBuilder(); builder.append("For these files:\n"); for (File file : files) { - builder.append(" " + file.getAbsolutePath() + "\n"); + builder.append(" ").append(file.getAbsolutePath()).append("\n"); } builder.append("a caching signature is being generated, which will be based only on their\n"); builder.append("names, not their full path (foo.txt, not C:\folder\foo.txt). Unexpectedly,\n"); @@ -99,7 +99,7 @@ private FileSignature(final List files) throws IOException { } /** A view of `FileSignature` which can be safely roundtripped. */ - public static class Promised implements Serializable { + public static final class Promised implements Serializable { @Serial private static final long serialVersionUID = 1L; private final List files; @@ -146,7 +146,7 @@ public File getOnlyFile() { } } - private static boolean machineIsWin = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win"); + private static final boolean machineIsWin = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win"); /** Returns true if this JVM is running on a windows machine. */ public static boolean machineIsWin() { diff --git a/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java index b64d82f2b5..7b980447c4 100644 --- a/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/FilterByContentPatternFormatterStep.java @@ -64,9 +64,9 @@ public boolean equals(Object o) { return false; } FilterByContentPatternFormatterStep that = (FilterByContentPatternFormatterStep) o; - return Objects.equals(delegateStep, that.delegateStep) && - Objects.equals(onMatch, that.onMatch) && - Objects.equals(contentPattern.pattern(), that.contentPattern.pattern()); + return Objects.equals(delegateStep, that.delegateStep) + && Objects.equals(onMatch, that.onMatch) + && Objects.equals(contentPattern.pattern(), that.contentPattern.pattern()); } @Override diff --git a/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java index 056984e584..7de0a32fbc 100644 --- a/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/FilterByFileFormatterStep.java @@ -61,8 +61,8 @@ public boolean equals(Object o) { return false; } FilterByFileFormatterStep that = (FilterByFileFormatterStep) o; - return Objects.equals(delegateStep, that.delegateStep) && - Objects.equals(filter, that.filter); + return Objects.equals(delegateStep, that.delegateStep) + && Objects.equals(filter, that.filter); } @Override diff --git a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java index c511b59997..d205e14039 100644 --- a/lib/src/main/java/com/diffplug/spotless/ForeignExe.java +++ b/lib/src/main/java/com/diffplug/spotless/ForeignExe.java @@ -39,7 +39,8 @@ public class ForeignExe implements Serializable { private @Nullable String pathToExe; private String versionFlag = "--version"; private Pattern versionRegex = Pattern.compile("version (\\S*)"); - private @Nullable String fixCantFind, fixWrongVersion; + private @Nullable String fixCantFind; + private @Nullable String fixWrongVersion; // MANDATORY private String name; diff --git a/lib/src/main/java/com/diffplug/spotless/Formatter.java b/lib/src/main/java/com/diffplug/spotless/Formatter.java index 1bd8c68d81..941667adb4 100644 --- a/lib/src/main/java/com/diffplug/spotless/Formatter.java +++ b/lib/src/main/java/com/diffplug/spotless/Formatter.java @@ -86,7 +86,7 @@ public static Formatter.Builder builder() { return new Formatter.Builder(); } - public static class Builder { + public static final class Builder { // required parameters private LineEnding.Policy lineEndingsPolicy; private Charset encoding; @@ -140,7 +140,7 @@ public String compute(String unix, File file) { } static void legacyErrorBehavior(Formatter formatter, File file, ValuePerStep exceptionPerStep) { - for (int i = 0; i < formatter.getSteps().size(); ++i) { + for (int i = 0; i < formatter.getSteps().size(); i++) { Throwable exception = exceptionPerStep.get(i); if (exception != null && exception != LintState.formatStepCausedNoChange()) { logger.error("Step '{}' found problem in '{}':\n{}", formatter.getSteps().get(i).getName(), file.getName(), exception.getMessage(), exception); @@ -165,7 +165,7 @@ String computeWithLint(String unix, File file, ValuePerStep exception Objects.requireNonNull(unix, "unix"); Objects.requireNonNull(file, "file"); - for (int i = 0; i < steps.size(); ++i) { + for (int i = 0; i < steps.size(); i++) { FormatterStep step = steps.get(i); Throwable storeForStep; try { @@ -200,8 +200,7 @@ public int hashCode() { int result = 1; result = prime * result + encoding.hashCode(); result = prime * result + lineEndingsPolicy.hashCode(); - result = prime * result + steps.hashCode(); - return result; + return prime * result + steps.hashCode(); } @Override @@ -216,9 +215,9 @@ public boolean equals(Object obj) { return false; } Formatter other = (Formatter) obj; - return encoding.equals(other.encoding) && - lineEndingsPolicy.equals(other.lineEndingsPolicy) && - steps.equals(other.steps); + return encoding.equals(other.encoding) + && lineEndingsPolicy.equals(other.lineEndingsPolicy) + && steps.equals(other.steps); } @SuppressWarnings("rawtypes") diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java b/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java index 6e75edafd0..0aaf1daea5 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatterProperties.java @@ -114,7 +114,7 @@ public static FormatterProperties fromXmlContent(final Iterable content) public static FormatterProperties merge(Properties... properties) { FormatterProperties merged = new FormatterProperties(); - List.of(properties).forEach(source -> merged.properties.putAll(source)); + List.of(properties).forEach(merged.properties::putAll); return merged; } diff --git a/lib/src/main/java/com/diffplug/spotless/FormatterStepSerializationRoundtrip.java b/lib/src/main/java/com/diffplug/spotless/FormatterStepSerializationRoundtrip.java index 77e9670380..15febb27ff 100644 --- a/lib/src/main/java/com/diffplug/spotless/FormatterStepSerializationRoundtrip.java +++ b/lib/src/main/java/com/diffplug/spotless/FormatterStepSerializationRoundtrip.java @@ -16,6 +16,7 @@ package com.diffplug.spotless; import java.io.IOException; +import java.io.ObjectOutputStream; import java.io.Serial; import java.io.Serializable; import java.util.Objects; @@ -66,7 +67,7 @@ protected FormatterFunc stateToFormatter(EqualityState equalityState) throws Exc return equalityStateToFormatter.apply(equalityState); } - private void writeObject(java.io.ObjectOutputStream out) throws IOException { + private void writeObject(ObjectOutputStream out) throws IOException { if (initializer == null) { // then this instance was created by Gradle's ConfigurationCacheHackList and the following will hold true if (roundtripStateInternal == null && equalityStateInternal == null) { @@ -108,7 +109,7 @@ static class HackClone that = (HackClone) o; return optimizeForEquality == that.optimizeForEquality && rehydrate().equals(that.rehydrate()); } diff --git a/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstaller.java b/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstaller.java index 40fe2f8c31..0226e409d8 100644 --- a/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstaller.java +++ b/lib/src/main/java/com/diffplug/spotless/GitPrePushHookInstaller.java @@ -39,7 +39,7 @@ public abstract class GitPrePushHookInstaller { private static final Object LOCK = new Object(); - private static volatile boolean installing = false; + private static volatile boolean installing; /** * Logger for recording informational and error messages during the installation process. @@ -57,7 +57,7 @@ public abstract class GitPrePushHookInstaller { * @param logger The logger for recording messages. * @param root The root directory of the Git repository. */ - public GitPrePushHookInstaller(GitPreHookLogger logger, File root) { + protected GitPrePushHookInstaller(GitPreHookLogger logger, File root) { this.logger = requireNonNull(logger, "logger can not be null"); this.root = requireNonNull(root, "root file can not be null"); } diff --git a/lib/src/main/java/com/diffplug/spotless/JarState.java b/lib/src/main/java/com/diffplug/spotless/JarState.java index cee030075d..f4ffffce8b 100644 --- a/lib/src/main/java/com/diffplug/spotless/JarState.java +++ b/lib/src/main/java/com/diffplug/spotless/JarState.java @@ -17,6 +17,8 @@ import java.io.File; import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.io.ObjectStreamException; import java.io.Serial; import java.io.Serializable; @@ -47,7 +49,7 @@ public final class JarState implements Serializable { private static final Logger logger = LoggerFactory.getLogger(JarState.class); // Let the classloader be overridden for tools using different approaches to classloading - @Nullable private static ClassLoader forcedClassLoader = null; + @Nullable private static ClassLoader forcedClassLoader; /** Overrides the classloader used by all JarStates. */ public static void setForcedClassLoader(@Nullable ClassLoader forcedClassLoader) { @@ -82,13 +84,13 @@ public JarState get() { } // override serialize output - private void writeObject(java.io.ObjectOutputStream out) + private void writeObject(ObjectOutputStream out) throws IOException { get(); out.defaultWriteObject(); } - private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); } diff --git a/lib/src/main/java/com/diffplug/spotless/Jvm.java b/lib/src/main/java/com/diffplug/spotless/Jvm.java index e9fa881a3f..e5c399f908 100644 --- a/lib/src/main/java/com/diffplug/spotless/Jvm.java +++ b/lib/src/main/java/com/diffplug/spotless/Jvm.java @@ -60,7 +60,7 @@ public static int version() { * Utility to map constraints of formatter to this JVM * @param Version type of formatter */ - public static class Support { + public static final class Support { static final String LINT_CODE = "jvm-version"; private final String fmtName; @@ -251,8 +251,8 @@ private String buildUpgradeFormatterMessage(V fmtVersion) { @Override public String toString() { - return "%s alternatives:%n".formatted(fmtName) + - jvm2fmtMaxVersion.entrySet().stream().map( + return "%s alternatives:%n".formatted(fmtName) + + jvm2fmtMaxVersion.entrySet().stream().map( e -> "- Version %s requires JVM %d+".formatted(e.getValue(), e.getKey())).collect(Collectors.joining(System.lineSeparator())); } @@ -289,7 +289,7 @@ private static int[] convert(V versionObject) { throw new IllegalArgumentException("Not a semantic version: %s".formatted(versionObject), e); } } - }; + } } /** @@ -300,6 +300,8 @@ private static int[] convert(V versionObject) { */ public static Support support(String formatterName) { Objects.requireNonNull(formatterName); - return new Support(formatterName); + return new Support<>(formatterName); } + + private Jvm() {} } diff --git a/lib/src/main/java/com/diffplug/spotless/LineEnding.java b/lib/src/main/java/com/diffplug/spotless/LineEnding.java index 3fbcb5afa0..225ba7b63a 100644 --- a/lib/src/main/java/com/diffplug/spotless/LineEnding.java +++ b/lib/src/main/java/com/diffplug/spotless/LineEnding.java @@ -126,7 +126,7 @@ static String getEndingFor(Reader reader) throws IOException { char currentCharacter = 0; int readResult; while ((readResult = reader.read()) != -1) { - currentCharacter = (char)readResult; + currentCharacter = (char) readResult; if (currentCharacter == '\n') { if (previousCharacter == '\r') { return WINDOWS.str(); diff --git a/lib/src/main/java/com/diffplug/spotless/Lint.java b/lib/src/main/java/com/diffplug/spotless/Lint.java index fb91232d8c..295b990d4b 100644 --- a/lib/src/main/java/com/diffplug/spotless/Lint.java +++ b/lib/src/main/java/com/diffplug/spotless/Lint.java @@ -45,7 +45,8 @@ public static Lint atLineRange(int lineStart, int lineEnd, String shortCode, Str @Serial private static final long serialVersionUID = 1L; - private int lineStart, lineEnd; // 1-indexed, inclusive + private int lineStart; + private int lineEnd; // 1-indexed, inclusive private String shortCode; // e.g. CN_IDIOM https://spotbugs.readthedocs.io/en/stable/bugDescriptions.html#cn-class-implements-cloneable-but-does-not-define-or-use-clone-method-cn-idiom private String detail; @@ -128,10 +129,12 @@ public String toString() { @Override public boolean equals(Object o) { - if (this == o) + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } Lint lint = (Lint) o; return lineStart == lint.lineStart && lineEnd == lint.lineEnd && Objects.equals(shortCode, lint.shortCode) && Objects.equals(detail, lint.detail); } @@ -182,7 +185,7 @@ private static int lineNumberFor(String message) { } private static String msgFrom(String message) { - for (int i = 0; i < message.length(); ++i) { + for (int i = 0; i < message.length(); i++) { if (Character.isLetter(message.charAt(i))) { return message.substring(i); } diff --git a/lib/src/main/java/com/diffplug/spotless/LintSuppression.java b/lib/src/main/java/com/diffplug/spotless/LintSuppression.java index 9221fe089d..852d6eeb98 100644 --- a/lib/src/main/java/com/diffplug/spotless/LintSuppression.java +++ b/lib/src/main/java/com/diffplug/spotless/LintSuppression.java @@ -17,11 +17,12 @@ import java.io.File; import java.io.Serial; +import java.io.Serializable; import java.util.Objects; import javax.annotation.Nullable; -public class LintSuppression implements java.io.Serializable { +public class LintSuppression implements Serializable { @Serial private static final long serialVersionUID = 1L; @@ -77,10 +78,12 @@ public void ensureDoesNotSuppressAll() { @Override public boolean equals(Object o) { - if (this == o) + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } LintSuppression that = (LintSuppression) o; return Objects.equals(path, that.path) && Objects.equals(step, that.step) && Objects.equals(shortCode, that.shortCode); } @@ -92,11 +95,11 @@ public int hashCode() { @Override public String toString() { - return "LintSuppression{" + - "file='" + path + '\'' + - ", step='" + step + '\'' + - ", code='" + shortCode + '\'' + - '}'; + return "LintSuppression{" + + "file='" + path + '\'' + + ", step='" + step + '\'' + + ", code='" + shortCode + '\'' + + '}'; } /** diff --git a/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java b/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java index 39d07b5888..05f5880129 100644 --- a/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java +++ b/lib/src/main/java/com/diffplug/spotless/ProcessRunner.java @@ -196,7 +196,8 @@ private void checkState() { public static class Result { private final List args; private final int exitCode; - private final byte[] stdOut, stdErr; + private final byte[] stdOut; + private final byte[] stdErr; public Result(@Nonnull List args, int exitCode, @Nonnull byte[] stdOut, @Nullable byte[] stdErr) { this.args = args; @@ -252,18 +253,18 @@ public String assertExitZero(Charset charset) { @Override public String toString() { StringBuilder builder = new StringBuilder(); - builder.append("> arguments: " + args + "\n"); - builder.append("> exit code: " + exitCode + "\n"); + builder.append("> arguments: ").append(args).append("\n"); + builder.append("> exit code: ").append(exitCode).append("\n"); BiConsumer perStream = (name, content) -> { String string = new String(content, Charset.defaultCharset()).trim(); if (string.isEmpty()) { - builder.append("> " + name + ": (empty)\n"); + builder.append("> ").append(name).append(": (empty)\n"); } else { String[] lines = string.replace("\r", "").split("\n"); if (lines.length == 1) { builder.append("> " + name + ": " + lines[0] + "\n"); } else { - builder.append("> " + name + ": (below)\n"); + builder.append("> ").append(name).append(": (below)\n"); for (String line : lines) { builder.append("> "); builder.append(line); diff --git a/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java b/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java index da4fc6aa04..86b7ecc370 100644 --- a/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.java +++ b/lib/src/main/java/com/diffplug/spotless/RingBufferByteArrayOutputStream.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. @@ -26,9 +26,9 @@ class RingBufferByteArrayOutputStream extends ByteArrayOutputStream { private final int limit; - private int zeroIndexPointer = 0; + private int zeroIndexPointer; - private boolean isOverLimit = false; + private boolean isOverLimit; public RingBufferByteArrayOutputStream(int limit) { this(limit, 32); diff --git a/lib/src/main/java/com/diffplug/spotless/TestingOnly.java b/lib/src/main/java/com/diffplug/spotless/TestingOnly.java index 89fb791789..82da66e0c4 100644 --- a/lib/src/main/java/com/diffplug/spotless/TestingOnly.java +++ b/lib/src/main/java/com/diffplug/spotless/TestingOnly.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. @@ -18,7 +18,7 @@ import java.util.Locale; /** These FormatterStep are meant to be used for testing only. */ -public class TestingOnly { +public final class TestingOnly { public static FormatterStep lowercase() { return FormatterStep.create("lowercase", "lowercaseStateUnused", unused -> TestingOnly::lowercase); } @@ -34,4 +34,6 @@ public static FormatterStep diverge() { private static String diverge(String raw) { return raw + " "; } + + private TestingOnly() {} } diff --git a/lib/src/main/java/com/diffplug/spotless/ValuePerStep.java b/lib/src/main/java/com/diffplug/spotless/ValuePerStep.java index 314bdc7e60..094edbb765 100644 --- a/lib/src/main/java/com/diffplug/spotless/ValuePerStep.java +++ b/lib/src/main/java/com/diffplug/spotless/ValuePerStep.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. @@ -27,7 +27,7 @@ class ValuePerStep extends AbstractList { private final int size; private @Nullable T value; private int valueIdx; - private @Nullable Object[] multipleValues = null; + private @Nullable Object[] multipleValues; ValuePerStep(Formatter formatter) { this.size = formatter.getSteps().size(); diff --git a/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4Defaults.java b/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4Defaults.java index 53223c087f..9c67a708df 100644 --- a/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4Defaults.java +++ b/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4Defaults.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package com.diffplug.spotless.antlr4; -public class Antlr4Defaults { +public final class Antlr4Defaults { private static final String LICENSE_HEADER_DELIMITER = "(grammar|lexer grammar|parser grammar)"; private static final String INCLUDES = "src/*/antlr4/**/*.g4"; diff --git a/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4FormatterStep.java b/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4FormatterStep.java index 1852cf35d9..31ed946244 100644 --- a/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4FormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4FormatterStep.java @@ -26,7 +26,7 @@ import com.diffplug.spotless.Provisioner; import com.diffplug.spotless.ThrowingEx; -public class Antlr4FormatterStep implements Serializable { +public final class Antlr4FormatterStep implements Serializable { @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATE = "com.khubla.antlr4formatter:antlr4-formatter:"; 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 9b580ead51..5d6134101a 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java @@ -42,7 +42,7 @@ * It delegates to the Biome executable. The Biome executable is downloaded from * the network when no executable path is provided explicitly. */ -public class BiomeStep { +public final class BiomeStep { private static final Logger logger = LoggerFactory.getLogger(BiomeStep.class); /** @@ -345,7 +345,7 @@ private String resolveExe() throws IOException, InterruptedException { * caching purposes. Spotless keeps a cache of which files need to be formatted. * The cache is busted when the serialized form of a state instance changes. */ - private static class State implements Serializable { + private static final class State implements Serializable { private static final long serialVersionUID = 6846790911054484379L; /** Path to the exe file */ diff --git a/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java b/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java index 39c1001725..7960670370 100644 --- a/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java @@ -32,7 +32,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -public class ClangFormatStep { +public final class ClangFormatStep { public static String name() { return "clang"; } @@ -80,8 +80,8 @@ private RoundtripState createRoundtrip() throws IOException, InterruptedExceptio .pathToExe(pathToExe) .fixCantFind(howToInstall) .fixWrongVersion( - "You can tell Spotless to use the version you already have with {@code clangFormat('{versionFound}')}" + - "or you can download the currently specified version, {version}.\n" + howToInstall); + "You can tell Spotless to use the version you already have with {@code clangFormat('{versionFound}')}" + + "or you can download the currently specified version, {version}.\n" + howToInstall); return new RoundtripState(this, exe); } diff --git a/lib/src/main/java/com/diffplug/spotless/cpp/CppDefaults.java b/lib/src/main/java/com/diffplug/spotless/cpp/CppDefaults.java index cf31b4a95c..9a577f11fb 100644 --- a/lib/src/main/java/com/diffplug/spotless/cpp/CppDefaults.java +++ b/lib/src/main/java/com/diffplug/spotless/cpp/CppDefaults.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,15 +19,15 @@ import java.util.stream.Collectors; /** Common utilities for C/C++ */ -public class CppDefaults { +public final class CppDefaults { //Prevent instantiation - private CppDefaults() {}; + private CppDefaults() {} /** - * Default delimiter expression shall cover most valid and common starts of C/C++ declarations and definitions. - * Furthermore it shall not conflict with terms commonly used within license headers. - * Note that the longest match is selected. Hence "using namespace foo" is preferred over "namespace foo". - */ + * Default delimiter expression shall cover most valid and common starts of C/C++ declarations and definitions. + * Furthermore it shall not conflict with terms commonly used within license headers. + * Note that the longest match is selected. Hence "using namespace foo" is preferred over "namespace foo". + */ public static final String DELIMITER_EXPR = Arrays.asList( "#define", "#error", "#if", "#ifdef", "#ifndef", "#include", "#pragma", "#undef", "asm", "class", "namespace", "struct", "typedef", "using namespace", @@ -37,8 +37,6 @@ public class CppDefaults { "int8_t", "int16_t", "int32_t", "int64_t", "__int8_t", "__int16_t", "__int32_t", "__int64_t", "uint8_t", "uint16_t", "uint32_t", "uint64_t") - .stream().map(s -> { - return "(? "(? createEnv() { File ideaProps = createIdeaPropertiesFile(); - Map env = Map.ofEntries( + return Map.ofEntries( Map.entry("IDEA_PROPERTIES", ThrowingEx.get(ideaProps::getCanonicalPath))); - return env; } private File createIdeaPropertiesFile() { diff --git a/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java b/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java index 1522adf947..00077f8c90 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java @@ -104,12 +104,12 @@ String format(String raw) { if (numSpaces > 0) { switch (state.type) { case SPACE: - for (int i = 0; i < numSpaces; ++i) { + for (int i = 0; i < numSpaces; i++) { builder.append(' '); } break; case TAB: - for (int i = 0; i < numSpaces / state.numSpacesPerTab; ++i) { + for (int i = 0; i < numSpaces / state.numSpacesPerTab; i++) { builder.append('\t'); } if (mightBeMultiLineComment && (numSpaces % state.numSpacesPerTab == 1)) { diff --git a/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java b/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java index fd634f50cf..7636f3606d 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/Jsr223Step.java @@ -80,8 +80,8 @@ FormatterFunc toFormatter() { ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(engine); if (scriptEngine == null) { - throw new IllegalArgumentException("Unknown script engine '" + engine + "'. Available engines: " + - scriptEngineManager.getEngineFactories().stream().flatMap(f -> f.getNames().stream()).collect(Collectors.joining(", "))); + throw new IllegalArgumentException("Unknown script engine '" + engine + "'. Available engines: " + + scriptEngineManager.getEngineFactories().stream().flatMap(f -> f.getNames().stream()).collect(Collectors.joining(", "))); } // evaluate script code diff --git a/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java b/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java index 941c1c376f..f4a58a5d27 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.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. @@ -174,8 +174,7 @@ private String sanitizeName(@Nullable String name) { return DEFAULT_NAME_PREFIX + "-" + name; } - @Nullable - private String sanitizePattern(@Nullable String pattern) { + @Nullable private String sanitizePattern(@Nullable String pattern) { if (pattern == null) { return pattern; } @@ -206,11 +205,11 @@ public static SerializableFileFilter unsupportedJvmFilesFilter() { public static final String spotlessSetLicenseHeaderYearsFromGitHistory = "spotlessSetLicenseHeaderYearsFromGitHistory"; - public static final String FLAG_SET_LICENSE_HEADER_YEARS_FROM_GIT_HISTORY() { + public static String FLAG_SET_LICENSE_HEADER_YEARS_FROM_GIT_HISTORY() { return spotlessSetLicenseHeaderYearsFromGitHistory; } - private static class Runtime implements Serializable { + private static final class Runtime implements Serializable { private static final long serialVersionUID = 1475199492829130965L; private final Pattern delimiterPattern; @@ -305,8 +304,7 @@ private String format(String raw, File file) { private String addOrUpdateLicenseHeader(String raw, File file) { raw = replaceYear(raw); - raw = replaceFileName(raw, file); - return raw; + return replaceFileName(raw, file); } private String replaceYear(String raw) { diff --git a/lib/src/main/java/com/diffplug/spotless/generic/NativeCmdStep.java b/lib/src/main/java/com/diffplug/spotless/generic/NativeCmdStep.java index 3e58c9dbae..d655fbefa5 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/NativeCmdStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/NativeCmdStep.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. @@ -28,7 +28,7 @@ import com.diffplug.spotless.FormatterStep; import com.diffplug.spotless.ProcessRunner; -public class NativeCmdStep { +public final class NativeCmdStep { // prevent direct instantiation private NativeCmdStep() {} diff --git a/lib/src/main/java/com/diffplug/spotless/generic/TestEnvVars.java b/lib/src/main/java/com/diffplug/spotless/generic/TestEnvVars.java index 8845fe9c0d..44278555aa 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/TestEnvVars.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/TestEnvVars.java @@ -22,11 +22,12 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Properties; import java.util.stream.Stream; import javax.annotation.Nullable; -class TestEnvVars { +final class TestEnvVars { private final Map envVars; @@ -48,7 +49,7 @@ private static Map readTestEnvVars() { Optional resolvedTestenvProps = candidateTestEnvLocations().filter(Files::exists).findFirst(); resolvedTestenvProps.ifPresent(testenvProps -> { try (var reader = Files.newBufferedReader(testenvProps)) { - java.util.Properties properties = new java.util.Properties(); + Properties properties = new Properties(); properties.load(reader); for (String name : properties.stringPropertyNames()) { envVars.put(name, properties.getProperty(name)); diff --git a/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsStep.java b/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsStep.java index de791303c0..aa68d7e6c7 100644 --- a/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/gherkin/GherkinUtilsStep.java @@ -26,7 +26,7 @@ import com.diffplug.spotless.JarState; import com.diffplug.spotless.Provisioner; -public class GherkinUtilsStep implements Serializable { +public final class GherkinUtilsStep implements Serializable { @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATE = "io.cucumber:gherkin-utils:"; diff --git a/lib/src/main/java/com/diffplug/spotless/go/GofmtFormatStep.java b/lib/src/main/java/com/diffplug/spotless/go/GofmtFormatStep.java index ffdc17cd21..a4354e89d2 100644 --- a/lib/src/main/java/com/diffplug/spotless/go/GofmtFormatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/go/GofmtFormatStep.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. @@ -37,7 +37,7 @@ * Note: gofmt doesn't have a version flag, because it's part of standard Go distribution. * So `go` executable can be used to determine base path and version, and path to gofmt can be built from it. */ -public class GofmtFormatStep { +public final class GofmtFormatStep { public static String name() { return "gofmt"; } @@ -67,15 +67,15 @@ public FormatterStep create() { } private RoundtripState createRountrip() throws IOException, InterruptedException { - String howToInstall = "gofmt is a part of standard go distribution. If spotless can't discover it automatically, " + - "you can point Spotless to the go binary with {@code pathToExe('/path/to/go')}"; + String howToInstall = "gofmt is a part of standard go distribution. If spotless can't discover it automatically, " + + "you can point Spotless to the go binary with {@code pathToExe('/path/to/go')}"; final ForeignExe exe = ForeignExe.nameAndVersion("go", version) .pathToExe(pathToExe) .versionFlag("version") .fixCantFind(howToInstall) .fixWrongVersion( - "You can tell Spotless to use the version you already have with {@code gofmt('{versionFound}')}" + - "or you can install the currently specified Go version, {version}.\n" + howToInstall); + "You can tell Spotless to use the version you already have with {@code gofmt('{versionFound}')}" + + "or you can install the currently specified Go version, {version}.\n" + howToInstall); return new RoundtripState(version, exe); } diff --git a/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java b/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java index ef10b7ec2f..ec18823d3a 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java @@ -174,7 +174,7 @@ private static final class State implements Serializable { this.includeDraft = includeDraft; } - private static class JvmSupportFormatterFunc implements FormatterFunc { + private static final class JvmSupportFormatterFunc implements FormatterFunc { final Object formatter; final Method formatterMethod; diff --git a/lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java b/lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java index 4ac3357426..793da7f272 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java @@ -27,7 +27,7 @@ import com.diffplug.spotless.Provisioner; /** Wraps up google-java-format as a FormatterStep. */ -public class GoogleJavaFormatStep implements Serializable { +public final class GoogleJavaFormatStep implements Serializable { @Serial private static final long serialVersionUID = 1L; private static final String DEFAULT_STYLE = "GOOGLE"; diff --git a/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java b/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java index 91c51e8cbe..e9e28c2576 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java +++ b/lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java @@ -267,7 +267,7 @@ private static int compareWithWildcare(String string1, String string2, boolean w return string1IsWildcard == wildcardsLast ? 1 : -1; } - private static class LexicographicalOrderingComparator implements Comparator, Serializable { + private static final class LexicographicalOrderingComparator implements Comparator, Serializable { private static final long serialVersionUID = 1; private final boolean wildcardsLast; @@ -282,7 +282,7 @@ public int compare(String string1, String string2) { } } - private static class SemanticOrderingComparator implements Comparator, Serializable { + private static final class SemanticOrderingComparator implements Comparator, Serializable { private static final long serialVersionUID = 1; private final boolean wildcardsLast; @@ -322,8 +322,9 @@ public int compare(String string1, String string2) { String member2 = split[1]; int result = compareFullyQualifiedClassName(fqcn1, fqcn2); - if (result != 0) + if (result != 0) { return result; + } return compareWithWildcare(member1, member2, wildcardsLast); } else { @@ -345,8 +346,9 @@ private int compareFullyQualifiedClassName(String fqcn1, String fqcn2) { String c2 = split[1]; int result = p1.compareTo(p2); - if (result != 0) + if (result != 0) { return result; + } return compareWithWildcare(c1, c2, wildcardsLast); } diff --git a/lib/src/main/java/com/diffplug/spotless/java/ModuleHelper.java b/lib/src/main/java/com/diffplug/spotless/java/ModuleHelper.java index 4466f96eaf..3023e2c20c 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/ModuleHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/java/ModuleHelper.java @@ -52,7 +52,7 @@ private ModuleHelper() {} REQUIRED_PACKAGES_TO_TEST_CLASSES.putIfAbsent("com.sun.tools.javac.api", "DiagnosticFormatter$PositionKind"); } - private static boolean checkDone = false; + private static boolean checkDone; public static synchronized void doOpenInternalPackagesIfRequired() { if (Jvm.version() < 16 || checkDone) { diff --git a/lib/src/main/java/com/diffplug/spotless/java/PalantirJavaFormatStep.java b/lib/src/main/java/com/diffplug/spotless/java/PalantirJavaFormatStep.java index 354f08e084..b717787d86 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/PalantirJavaFormatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/PalantirJavaFormatStep.java @@ -28,7 +28,7 @@ /** Wraps up palantir-java-format fork of * google-java-format as a FormatterStep. */ -public class PalantirJavaFormatStep implements Serializable { +public final class PalantirJavaFormatStep implements Serializable { @Serial private static final long serialVersionUID = 1L; private static final boolean DEFAULT_FORMAT_JAVADOC = false; diff --git a/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java b/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java index 187ee8b6a4..590432aedc 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java @@ -24,7 +24,7 @@ import com.diffplug.spotless.Provisioner; /** Uses google-java-format or cleanthat.UnnecessaryImport, but only to remove unused imports. */ -public class RemoveUnusedImportsStep implements Serializable { +public final class RemoveUnusedImportsStep implements Serializable { @Serial private static final long serialVersionUID = 1L; static final String NAME = "removeUnusedImports"; diff --git a/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonConfig.java b/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonConfig.java index 41a5501fc2..9c9578c97e 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonConfig.java @@ -31,7 +31,7 @@ public class JacksonJsonConfig extends JacksonConfig { // https://github.com/revelc/formatter-maven-plugin/pull/280 // By default, Jackson adds a ' ' before separator, which is not standard with most IDE/JSON libraries - protected boolean spaceBeforeSeparator = false; + protected boolean spaceBeforeSeparator; public Map getJsonFeatureToToggle() { return Collections.unmodifiableMap(jsonFeatureToToggle); diff --git a/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonStep.java b/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonStep.java index c56921458c..ec2a9726c3 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonStep.java +++ b/lib/src/main/java/com/diffplug/spotless/json/JacksonJsonStep.java @@ -30,7 +30,7 @@ * Simple YAML formatter which reformats the file according to Jackson YAMLFactory. */ // https://stackoverflow.com/questions/14515994/convert-json-string-to-pretty-print-json-output-using-jackson -public class JacksonJsonStep implements Serializable { +public final class JacksonJsonStep implements Serializable { @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATE = "com.fasterxml.jackson.core:jackson-databind:"; diff --git a/lib/src/main/java/com/diffplug/spotless/json/JsonPatchStep.java b/lib/src/main/java/com/diffplug/spotless/json/JsonPatchStep.java index 0b5f4c9d73..dce0c3a307 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/JsonPatchStep.java +++ b/lib/src/main/java/com/diffplug/spotless/json/JsonPatchStep.java @@ -30,7 +30,7 @@ import com.diffplug.spotless.JarState; import com.diffplug.spotless.Provisioner; -public class JsonPatchStep implements Serializable { +public final class JsonPatchStep implements Serializable { @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATE = "com.flipkart.zjsonpatch:zjsonpatch"; diff --git a/lib/src/main/java/com/diffplug/spotless/json/gson/GsonStep.java b/lib/src/main/java/com/diffplug/spotless/json/gson/GsonStep.java index de11c4d9d9..5ad4034bb6 100644 --- a/lib/src/main/java/com/diffplug/spotless/json/gson/GsonStep.java +++ b/lib/src/main/java/com/diffplug/spotless/json/gson/GsonStep.java @@ -26,7 +26,7 @@ import com.diffplug.spotless.JarState; import com.diffplug.spotless.Provisioner; -public class GsonStep implements Serializable { +public final class GsonStep implements Serializable { @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATES = "com.google.code.gson:gson"; diff --git a/lib/src/main/java/com/diffplug/spotless/kotlin/BadSemver.java b/lib/src/main/java/com/diffplug/spotless/kotlin/BadSemver.java index 771c27eb3e..24d9586d31 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/BadSemver.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/BadSemver.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2022 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -class BadSemver { +final class BadSemver { protected static int version(String input) { Matcher matcher = BAD_SEMVER.matcher(input); if (!matcher.find() || matcher.start() != 0) { @@ -40,4 +40,6 @@ protected static int version(int major, int minor) { } private static final Pattern BAD_SEMVER = Pattern.compile("(\\d+)\\.(\\d+)\\.*(\\d+)*"); + + private BadSemver() {} } diff --git a/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java b/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java index 4f08bd21ce..8efe5a61b7 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/DiktatStep.java @@ -30,7 +30,7 @@ import com.diffplug.spotless.Provisioner; /** Wraps up diktat as a FormatterStep. */ -public class DiktatStep implements Serializable { +public final class DiktatStep implements Serializable { @Serial private static final long serialVersionUID = 1L; private final JarState.Promised jarState; diff --git a/lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java b/lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java index 7cdd102b10..c022af784d 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java @@ -35,7 +35,7 @@ import com.diffplug.spotless.Provisioner; /** Wraps up ktlint as a FormatterStep. */ -public class KtLintStep implements Serializable { +public final class KtLintStep implements Serializable { @Serial private static final long serialVersionUID = 1L; private static final String DEFAULT_VERSION = "1.7.1"; diff --git a/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java b/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java index 0f1abf1320..575debf9c0 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java @@ -39,7 +39,7 @@ /** * Wraps up ktfmt as a FormatterStep. */ -public class KtfmtStep implements Serializable { +public final class KtfmtStep implements Serializable { @Serial private static final long serialVersionUID = 1L; private static final String DEFAULT_VERSION = "0.58"; @@ -147,13 +147,13 @@ public static class KtfmtFormattingOptions implements Serializable { @Serial private static final long serialVersionUID = 1L; - @Nullable private Integer maxWidth = null; + @Nullable private Integer maxWidth; - @Nullable private Integer blockIndent = null; + @Nullable private Integer blockIndent; - @Nullable private Integer continuationIndent = null; + @Nullable private Integer continuationIndent; - @Nullable private Boolean removeUnusedImports = null; + @Nullable private Boolean removeUnusedImports; @Nullable private TrailingCommaManagementStrategy trailingCommaManagementStrategy; diff --git a/lib/src/main/java/com/diffplug/spotless/markdown/FlexmarkStep.java b/lib/src/main/java/com/diffplug/spotless/markdown/FlexmarkStep.java index bce55abb69..91ac81d847 100644 --- a/lib/src/main/java/com/diffplug/spotless/markdown/FlexmarkStep.java +++ b/lib/src/main/java/com/diffplug/spotless/markdown/FlexmarkStep.java @@ -26,7 +26,7 @@ import com.diffplug.spotless.Provisioner; /** A step for flexmark-java. */ -public class FlexmarkStep implements Serializable { +public final class FlexmarkStep implements Serializable { @Serial private static final long serialVersionUID = 1L; private static final String DEFAULT_VERSION = "0.64.8"; diff --git a/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java b/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java index 6149a736e1..b08148d8c8 100644 --- a/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java +++ b/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java @@ -38,7 +38,7 @@ import com.diffplug.spotless.Provisioner; /** A step for FreshMark. */ -public class FreshMarkStep implements Serializable { +public final class FreshMarkStep implements Serializable { @Serial private static final long serialVersionUID = 1L; 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 d85b4d7a8c..b2a30a5278 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java @@ -39,7 +39,7 @@ import com.diffplug.spotless.ThrowingEx; import com.diffplug.spotless.npm.EslintRestService.FormatOption; -public class EslintFormatterStep { +public final class EslintFormatterStep { private static final Logger logger = LoggerFactory.getLogger(EslintFormatterStep.class); @@ -182,4 +182,6 @@ private void setConfigToCallOptions(Map eslintCallOptions) } } } + + private EslintFormatterStep() {} } 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 f36fcbb8b4..2b8c542ba8 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/ExclusiveFolderAccess.java @@ -37,7 +37,7 @@ static ExclusiveFolderAccess forFolder(@Nonnull String path) { void runExclusively(ThrowingEx.Runnable runnable); - class ExclusiveFolderAccessSharedMutex implements ExclusiveFolderAccess { + final class ExclusiveFolderAccessSharedMutex implements ExclusiveFolderAccess { private static final ConcurrentHashMap mutexes = new ConcurrentHashMap<>(); diff --git a/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java b/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java index d674621261..b1f45a0455 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/FileFinder.java @@ -26,7 +26,7 @@ import java.util.function.Predicate; import java.util.function.Supplier; -class FileFinder { +final class FileFinder { private final List>> fileCandidateFinders; diff --git a/lib/src/main/java/com/diffplug/spotless/npm/JsonRawValue.java b/lib/src/main/java/com/diffplug/spotless/npm/JsonRawValue.java index 332dfb7c17..b67045d85e 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/JsonRawValue.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/JsonRawValue.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ /** * Wrapper class to signal the contained string must not be escaped when printing to json. */ -class JsonRawValue { +final class JsonRawValue { private final String rawJson; private JsonRawValue(String rawJson) { 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 24ae62fde6..aa4a96b885 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/ListableAdapter.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/ListableAdapter.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. @@ -22,7 +22,7 @@ import javax.annotation.Nonnull; -class ListableAdapter implements Iterable { +final class ListableAdapter implements Iterable { private final List delegate; diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeExecutableResolver.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeExecutableResolver.java index 832bcd97a8..19b3ef7d8a 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeExecutableResolver.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeExecutableResolver.java @@ -18,7 +18,7 @@ import java.io.File; import java.util.Optional; -class NodeExecutableResolver { +final class NodeExecutableResolver { private NodeExecutableResolver() { // no instance 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 390e515c5e..ae8ff3afa8 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeModulesCachingNpmProcessFactory.java @@ -27,7 +27,7 @@ import com.diffplug.spotless.ProcessRunner.Result; -public class NodeModulesCachingNpmProcessFactory implements NpmProcessFactory { +public final class NodeModulesCachingNpmProcessFactory implements NpmProcessFactory { private static final Logger logger = LoggerFactory.getLogger(NodeModulesCachingNpmProcessFactory.class); diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java index 1fc9ad324e..d90ecf8b19 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmExecutableResolver.java @@ -35,7 +35,7 @@ * * */ -class NpmExecutableResolver { +final class NpmExecutableResolver { private static final FileFinder NPM_EXECUTABLE_FINDER = FileFinder.finderForExecutableFilename(npmExecutableName()) .candidateSystemProperty("npm.exec") diff --git a/lib/src/main/java/com/diffplug/spotless/npm/PlatformInfo.java b/lib/src/main/java/com/diffplug/spotless/npm/PlatformInfo.java index 3ae624d7c0..2b2b5541d7 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PlatformInfo.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PlatformInfo.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ import java.util.Locale; -class PlatformInfo { +final class PlatformInfo { private PlatformInfo() { // no instance } 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 aa12e64407..a9382bf6c3 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java @@ -35,7 +35,7 @@ import com.diffplug.spotless.Provisioner; import com.diffplug.spotless.ThrowingEx; -public class PrettierFormatterStep { +public final class PrettierFormatterStep { private static final Logger logger = LoggerFactory.getLogger(PrettierFormatterStep.class); @@ -43,11 +43,11 @@ public class PrettierFormatterStep { public static final String DEFAULT_VERSION = "2.8.8"; - public static final Map defaultDevDependencies() { + public static Map defaultDevDependencies() { return defaultDevDependenciesWithPrettier(DEFAULT_VERSION); } - public static final Map defaultDevDependenciesWithPrettier(String version) { + public static Map defaultDevDependenciesWithPrettier(String version) { return Collections.singletonMap("prettier", version); } @@ -148,4 +148,6 @@ private String assertFilepathInConfigOptions(File file) { } } + private PrettierFormatterStep() {} + } 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 c17812ddda..02b5c8fb82 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierMissingParserException.java @@ -113,7 +113,7 @@ private static String guessPlugin(File file) { return EXTENSIONS_TO_PLUGINS.entrySet().stream() .filter(entry -> file.getName().endsWith(entry.getKey())) .findFirst() - .map(entry -> entry.getValue()) + .map(Map.Entry::getValue) .orElse("prettier-plugin-" + extension(file)); } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/SimpleRestClient.java b/lib/src/main/java/com/diffplug/spotless/npm/SimpleRestClient.java index ef72c20721..ceeaf2e49a 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/SimpleRestClient.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/SimpleRestClient.java @@ -28,7 +28,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -class SimpleRestClient { +final class SimpleRestClient { private final String baseUrl; private SimpleRestClient(String baseUrl) { @@ -72,8 +72,7 @@ String postJson(String endpoint, @Nullable String rawJson) throws SimpleRestExce throw new SimpleRestResponseException(status, readError(con), "Unexpected response status code at " + endpoint); } - String response = readResponse(con); - return response; + return readResponse(con); } catch (IOException e) { throw new SimpleRestIOException(e); } @@ -96,9 +95,9 @@ private String readInputStream(InputStream inputStream) throws IOException { abstract static class SimpleRestException extends RuntimeException { private static final long serialVersionUID = -8260821395756603787L; - public SimpleRestException() {} + protected SimpleRestException() {} - public SimpleRestException(Throwable cause) { + protected SimpleRestException(Throwable cause) { super(cause); } } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/StandardNpmProcessFactory.java b/lib/src/main/java/com/diffplug/spotless/npm/StandardNpmProcessFactory.java index bb618d016c..7b95db7740 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/StandardNpmProcessFactory.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/StandardNpmProcessFactory.java @@ -24,7 +24,7 @@ import com.diffplug.spotless.ProcessRunner; -public class StandardNpmProcessFactory implements NpmProcessFactory { +public final class StandardNpmProcessFactory implements NpmProcessFactory { public static final StandardNpmProcessFactory INSTANCE = new StandardNpmProcessFactory(); @@ -48,7 +48,7 @@ private abstract static class AbstractStandardNpmProcess { protected final File workingDir; protected final NpmFormatterStepLocations formatterStepLocations; - public AbstractStandardNpmProcess(File workingDir, NpmFormatterStepLocations formatterStepLocations) { + protected AbstractStandardNpmProcess(File workingDir, NpmFormatterStepLocations formatterStepLocations) { this.formatterStepLocations = formatterStepLocations; this.workingDir = workingDir; } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/TimedLogger.java b/lib/src/main/java/com/diffplug/spotless/npm/TimedLogger.java index 537234fcee..eaf51320c4 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/TimedLogger.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/TimedLogger.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. @@ -30,7 +30,7 @@ /** * A logger that logs the time it took to execute a block of code. */ -class TimedLogger { +final class TimedLogger { public static final String MESSAGE_PREFIX_BEGIN = "[BEGIN] "; @@ -158,7 +158,7 @@ static Ticker systemTicker() { } static class TestTicker implements Ticker { - private long time = 0; + private long time; @Override public long read() { 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 f013a255e6..787b14c9c9 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java @@ -36,7 +36,7 @@ import com.diffplug.spotless.Provisioner; import com.diffplug.spotless.ThrowingEx; -public class TsFmtFormatterStep { +public final class TsFmtFormatterStep { private static final Logger logger = LoggerFactory.getLogger(TsFmtFormatterStep.class); @@ -126,4 +126,6 @@ private void endServer(TsFmtRestService restService, ServerProcessInfo restServe restServer.close(); } } + + private TsFmtFormatterStep() {} } diff --git a/lib/src/main/java/com/diffplug/spotless/pom/SortPomCfg.java b/lib/src/main/java/com/diffplug/spotless/pom/SortPomCfg.java index 15bb77fee2..9825cfa4d8 100644 --- a/lib/src/main/java/com/diffplug/spotless/pom/SortPomCfg.java +++ b/lib/src/main/java/com/diffplug/spotless/pom/SortPomCfg.java @@ -31,7 +31,7 @@ public class SortPomCfg implements Serializable { public boolean expandEmptyElements; - public boolean spaceBeforeCloseEmptyElement = false; + public boolean spaceBeforeCloseEmptyElement; public boolean keepBlankLines = true; @@ -39,29 +39,29 @@ public class SortPomCfg implements Serializable { public int nrOfIndentSpace = 2; - public boolean indentBlankLines = false; + public boolean indentBlankLines; - public boolean indentSchemaLocation = false; + public boolean indentSchemaLocation; - public String indentAttribute = null; + public String indentAttribute; public String predefinedSortOrder = "recommended_2008_06"; - public boolean quiet = false; + public boolean quiet; - public String sortOrderFile = null; + public String sortOrderFile; - public String sortDependencies = null; + public String sortDependencies; - public String sortDependencyManagement = null; + public String sortDependencyManagement; - public String sortDependencyExclusions = null; + public String sortDependencyExclusions; - public String sortPlugins = null; + public String sortPlugins; - public boolean sortProperties = false; + public boolean sortProperties; - public boolean sortModules = false; + public boolean sortModules; - public boolean sortExecutions = false; + public boolean sortExecutions; } diff --git a/lib/src/main/java/com/diffplug/spotless/pom/SortPomStep.java b/lib/src/main/java/com/diffplug/spotless/pom/SortPomStep.java index e4c658f855..978ea3128b 100644 --- a/lib/src/main/java/com/diffplug/spotless/pom/SortPomStep.java +++ b/lib/src/main/java/com/diffplug/spotless/pom/SortPomStep.java @@ -25,7 +25,7 @@ import com.diffplug.spotless.JarState; import com.diffplug.spotless.Provisioner; -public class SortPomStep implements Serializable { +public final class SortPomStep implements Serializable { @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATE = "com.github.ekryd.sortpom:sortpom-sorter:"; diff --git a/lib/src/main/java/com/diffplug/spotless/protobuf/BufStep.java b/lib/src/main/java/com/diffplug/spotless/protobuf/BufStep.java index e623bd0b51..c499d113f7 100644 --- a/lib/src/main/java/com/diffplug/spotless/protobuf/BufStep.java +++ b/lib/src/main/java/com/diffplug/spotless/protobuf/BufStep.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. @@ -32,7 +32,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -public class BufStep { +public final class BufStep { public static String name() { return "buf"; } diff --git a/lib/src/main/java/com/diffplug/spotless/protobuf/ProtobufConstants.java b/lib/src/main/java/com/diffplug/spotless/protobuf/ProtobufConstants.java index cd91e2671c..f4882bd2fe 100644 --- a/lib/src/main/java/com/diffplug/spotless/protobuf/ProtobufConstants.java +++ b/lib/src/main/java/com/diffplug/spotless/protobuf/ProtobufConstants.java @@ -1,5 +1,5 @@ /* - * Copyright 2022-2023 DiffPlug + * Copyright 2022-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,8 @@ */ package com.diffplug.spotless.protobuf; -public class ProtobufConstants { +public final class ProtobufConstants { public static final String LICENSE_HEADER_DELIMITER = "syntax"; + + private ProtobufConstants() {} } diff --git a/lib/src/main/java/com/diffplug/spotless/python/BlackStep.java b/lib/src/main/java/com/diffplug/spotless/python/BlackStep.java index 46d00caab2..3de571c889 100644 --- a/lib/src/main/java/com/diffplug/spotless/python/BlackStep.java +++ b/lib/src/main/java/com/diffplug/spotless/python/BlackStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2024 DiffPlug + * Copyright 2020-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -public class BlackStep { +public final class BlackStep { public static String name() { return "black"; } diff --git a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterConfig.java b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterConfig.java index 9e9f62d408..db63902f2d 100644 --- a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterConfig.java +++ b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterConfig.java @@ -92,10 +92,12 @@ public RdfFormatterConfig build() { @Override public boolean equals(Object o) { - if (this == o) + if (this == o) { return true; - if (!(o instanceof RdfFormatterConfig)) + } + if (!(o instanceof RdfFormatterConfig)) { return false; + } RdfFormatterConfig that = (RdfFormatterConfig) o; return isFailOnWarning() == that.isFailOnWarning() && Objects.equals(turtleFormatterVersion, that.turtleFormatterVersion); diff --git a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterFunc.java b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterFunc.java index 83e8775edf..da3960b8f6 100644 --- a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterFunc.java +++ b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterFunc.java @@ -153,9 +153,9 @@ private static String calculateDiff(ReflectionHelper reflectionHelper, Object mo }) .collect(Collectors.toList()); if (!(onlyInBeforeContent.isEmpty() && onlyInAfterContent.isEmpty())) { - diffResult = onlyInBeforeContent.stream().map(s -> "< %s".formatted(s)) + diffResult = onlyInBeforeContent.stream().map("< %s"::formatted) .collect(Collectors.joining("\n")); - diffResult += "\n" + onlyInAfterContent.stream().map(s -> "> %s".formatted(s)).collect(Collectors.joining("\n")); + diffResult += "\n" + onlyInAfterContent.stream().map("> %s"::formatted).collect(Collectors.joining("\n")); } else { diffResult = "'before' and 'after' content differs, but we don't know why. This is probably a bug."; } diff --git a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterStep.java index 0c5b21d66d..dce13ea0f5 100644 --- a/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/rdf/RdfFormatterStep.java @@ -92,10 +92,12 @@ public JarState getJarState() { @Override public boolean equals(Object o) { - if (this == o) + if (this == o) { return true; - if (!(o instanceof State)) + } + if (!(o instanceof State)) { return false; + } State state = (State) o; return Objects.equals(getConfig(), state.getConfig()) && Objects.equals( getTurtleFormatterStyle(), state.getTurtleFormatterStyle()) 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 3260b28e1d..94090045c5 100644 --- a/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/rdf/ReflectionHelper.java @@ -76,8 +76,8 @@ class ReflectionHelper { private final Method getGraph; private final Method tripleGetObject; - private Object turtleFormatter = null; - private Object jenaModelInstance = null; + private Object turtleFormatter; + private final Object jenaModelInstance; public ReflectionHelper(RdfFormatterStep.State state) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { @@ -271,8 +271,7 @@ private Object newTurtleFormatterStyle() throws IllegalAccessException, Invocati Method method = getBuilderMethod(optionName); callBuilderMethod(builder, method, state.getTurtleFormatterStyle().get(optionName)); } - Object style = TurtleFormatFormattingStyleBuilderClass.getMethod("build").invoke(builder); - return style; + return TurtleFormatFormattingStyleBuilderClass.getMethod("build").invoke(builder); } public String formatWithTurtleFormatter(String ttlContent) @@ -284,9 +283,8 @@ public String formatWithTurtleFormatter(String ttlContent) private Object newTurtleFormatter(Object style) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { - Object formatter = TurtleFormatFormatterClass.getConstructor(TurtleFormatFormattingStyleClass) + return TurtleFormatFormatterClass.getConstructor(TurtleFormatFormattingStyleClass) .newInstance(style); - return formatter; } private void callBuilderMethod(Object builder, Method method, String parameterValueAsString) @@ -346,14 +344,13 @@ private void callBuilderMethod(Object builder, Method method, String parameterVa private Object makeListOf(Type type, String parameterValueAsString) { String[] entries = split(parameterValueAsString); - List ret = Arrays.stream(entries).map(e -> { + return Arrays.stream(entries).map(e -> { try { return instantiate(type, e); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { throw new RuntimeException(ex); } }).collect(Collectors.toList()); - return ret; } private Object makeSetOf(Type type, String parameterValueAsString) { diff --git a/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java b/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java index 32378db4db..30319a117b 100644 --- a/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java +++ b/lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java @@ -31,7 +31,7 @@ import com.diffplug.spotless.Provisioner; /** Wraps up scalafmt as a FormatterStep. */ -public class ScalaFmtStep implements Serializable { +public final class ScalaFmtStep implements Serializable { @Serial private static final long serialVersionUID = 1L; diff --git a/lib/src/main/java/com/diffplug/spotless/shell/ShfmtStep.java b/lib/src/main/java/com/diffplug/spotless/shell/ShfmtStep.java index 9e3feba31e..798dfb4957 100644 --- a/lib/src/main/java/com/diffplug/spotless/shell/ShfmtStep.java +++ b/lib/src/main/java/com/diffplug/spotless/shell/ShfmtStep.java @@ -34,7 +34,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -public class ShfmtStep { +public final class ShfmtStep { public static String name() { return "shfmt"; } @@ -77,8 +77,8 @@ private RoundtripState createRoundtrip() throws IOException, InterruptedExceptio .versionRegex(Pattern.compile("([\\d.]+)")) .fixCantFind(howToInstall) .fixWrongVersion( - "You can tell Spotless to use the version you already have with {@code shfmt('{versionFound}')}" + - "or you can download the currently specified version, {version}.\n" + howToInstall); + "You can tell Spotless to use the version you already have with {@code shfmt('{versionFound}')}" + + "or you can download the currently specified version, {version}.\n" + howToInstall); return new RoundtripState(version, exe); } diff --git a/lib/src/main/java/com/diffplug/spotless/sql/DBeaverSQLFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/sql/DBeaverSQLFormatterStep.java index e9c7a59e54..fe3dd36486 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/DBeaverSQLFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/DBeaverSQLFormatterStep.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. @@ -23,7 +23,7 @@ import com.diffplug.spotless.FormatterStep; /** SQL formatter step which wraps up DBeaver's SqlTokenizedFormatter implementation. */ -public class DBeaverSQLFormatterStep { +public final class DBeaverSQLFormatterStep { private static final String NAME = "dbeaverSql"; diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLConstants.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLConstants.java index 698c87458f..c32be9ad26 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLConstants.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLConstants.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. @@ -23,7 +23,7 @@ * Based on SQLConstants from https://github.com/serge-rider/dbeaver, * which itself is licensed under the Apache 2.0 license. */ -class SQLConstants { +final class SQLConstants { static final String ML_COMMENT_START = "/*"; static final String ML_COMMENT_END = "*/"; @@ -567,6 +567,8 @@ class SQLConstants { "BLOB", }; - static final char STRUCT_SEPARATOR = '.'; //$NON-NLS-1$ + static final char STRUCT_SEPARATOR = '.'; + + private SQLConstants() {} //$NON-NLS-1$ } diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLDialect.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLDialect.java index daabd5386b..08b4e1a46c 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLDialect.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLDialect.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-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. @@ -31,7 +31,7 @@ * Based on SQLDialect from https://github.com/serge-rider/dbeaver, * which itself is licensed under the Apache 2.0 license. */ -class SQLDialect { +final class SQLDialect { private static final String[] DEFAULT_LINE_COMMENTS = {SQLConstants.SL_COMMENT}; private static final String[] EXEC_KEYWORDS = new String[0]; @@ -39,12 +39,12 @@ class SQLDialect { private static final String[][] DEFAULT_QUOTE_STRINGS = {{"\"", "\""}}; // Keywords - private TreeMap allKeywords = new TreeMap<>(); + private final TreeMap allKeywords = new TreeMap<>(); private final TreeSet functions = new TreeSet<>(); private final TreeSet types = new TreeSet<>(); // Comments - private Pair multiLineComments = new Pair<>(SQLConstants.ML_COMMENT_START, SQLConstants.ML_COMMENT_END); + private final Pair multiLineComments = new Pair<>(SQLConstants.ML_COMMENT_START, SQLConstants.ML_COMMENT_END); static final SQLDialect INSTANCE = new SQLDialect(); diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokenizedFormatter.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokenizedFormatter.java index 03efa19dad..98793d2480 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 @@ -124,8 +124,8 @@ private List format(final List argList) { String token2String = t2.getString().toUpperCase(Locale.ENGLISH); // Concatenate tokens if (t0.getType() == TokenType.KEYWORD && t1.getType() == TokenType.SPACE && t2.getType() == TokenType.KEYWORD) { - if ((("ORDER".equals(tokenString) || "GROUP".equals(tokenString) || "CONNECT".equals(tokenString)) && "BY".equals(token2String)) || - (("START".equals(tokenString)) && "WITH".equals(token2String))) { + if ((("ORDER".equals(tokenString) || "GROUP".equals(tokenString) || "CONNECT".equals(tokenString)) && "BY".equals(token2String)) + || (("START".equals(tokenString)) && "WITH".equals(token2String))) { t0.setString(t0.getString() + " " + t2.getString()); argList.remove(index + 1); argList.remove(index + 1); @@ -308,9 +308,9 @@ private List format(final List argList) { prev = argList.get(index - 1); token = argList.get(index); - if (prev.getType() != TokenType.SPACE && - token.getType() != TokenType.SPACE && - !token.getString().startsWith("(")) { + if (prev.getType() != TokenType.SPACE + && token.getType() != TokenType.SPACE + && !token.getString().startsWith("(")) { if (",".equals(token.getString()) || statementDelimiters.contains(token.getString())) { continue; } @@ -322,8 +322,8 @@ private List format(final List argList) { // Do not add space between name and value [JDBC:MSSQL] continue; } - if (token.getType() == TokenType.SYMBOL && isEmbeddedToken(token) || - prev.getType() == TokenType.SYMBOL && isEmbeddedToken(prev)) { + if (token.getType() == TokenType.SYMBOL && isEmbeddedToken(token) + || prev.getType() == TokenType.SYMBOL && isEmbeddedToken(prev)) { // Do not insert spaces around colons continue; } @@ -393,8 +393,9 @@ private static String getDefaultLineSeparator() { } private int insertReturnAndIndent(final List argList, final int argIndex, final int argIndent) { - if (functionBracket.contains(Boolean.TRUE)) + if (functionBracket.contains(Boolean.TRUE)) { return 0; + } try { final String defaultLineSeparator = getDefaultLineSeparator(); StringBuilder s = new StringBuilder(defaultLineSeparator); @@ -404,9 +405,9 @@ private int insertReturnAndIndent(final List argList, final int if (argIndex > 0) { final FormatterToken token = argList.get(argIndex); final FormatterToken prevToken = argList.get(argIndex - 1); - if (token.getType() == TokenType.COMMENT && - isCommentLine(sqlDialect, token.getString()) && - prevToken.getType() != TokenType.END) { + if (token.getType() == TokenType.COMMENT + && isCommentLine(sqlDialect, token.getString()) + && prevToken.getType() != TokenType.END) { s.setCharAt(0, ' '); s.setLength(1); @@ -456,11 +457,13 @@ private static boolean isCommentLine(SQLDialect dialect, String line) { } private static boolean contains(OBJECT_TYPE[] array, OBJECT_TYPE value) { - if (array == null || array.length == 0) + if (array == null || array.length == 0) { return false; + } for (OBJECT_TYPE anArray : array) { - if (Objects.equals(value, anArray)) + if (Objects.equals(value, anArray)) { return true; + } } return false; } 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 b1931c3c4c..f80b084c91 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java @@ -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. @@ -35,13 +35,13 @@ class SQLTokensParser { private static final SQLDialect sqlDialect = SQLDialect.INSTANCE; private final String[][] quoteStrings; - private String fBefore = null; + private final char structSeparator; + private final String catalogSeparator; + private final Set commands = new HashSet<>(); + private final String[] singleLineComments; + private final char[] singleLineCommentStart; + private String fBefore = ""; private int fPos; - private char structSeparator; - private String catalogSeparator; - private Set commands = new HashSet<>(); - private String[] singleLineComments; - private char[] singleLineCommentStart; SQLTokensParser() { this.structSeparator = sqlDialect.getStructSeparator(); @@ -50,10 +50,11 @@ class SQLTokensParser { this.singleLineComments = sqlDialect.getSingleLineComments(); this.singleLineCommentStart = new char[this.singleLineComments.length]; for (int i = 0; i < singleLineComments.length; i++) { - if (singleLineComments[i].isEmpty()) + if (singleLineComments[i].isEmpty()) { singleLineCommentStart[i] = 0; - else + } else { singleLineCommentStart[i] = singleLineComments[i].charAt(0); + } } } @@ -292,11 +293,13 @@ List parse(final String argSql) { } private static boolean contains(char[] array, char value) { - if (array == null || array.length == 0) + if (array == null) { return false; + } for (char aChar : array) { - if (aChar == value) + if (aChar == value) { return true; + } } return false; } diff --git a/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlStep.java b/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlStep.java index 58ffea7816..36b10fa061 100644 --- a/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlStep.java +++ b/lib/src/main/java/com/diffplug/spotless/yaml/JacksonYamlStep.java @@ -31,7 +31,7 @@ */ // https://stackoverflow.com/questions/14515994/convert-json-string-to-pretty-print-json-output-using-jackson // https://stackoverflow.com/questions/60891174/i-want-to-load-a-yaml-file-possibly-edit-the-data-and-then-dump-it-again-how -public class JacksonYamlStep implements Serializable { +public final class JacksonYamlStep implements Serializable { @Serial private static final long serialVersionUID = 1L; private static final String MAVEN_COORDINATE = "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:"; diff --git a/lib/src/scalafmt/java/com/diffplug/spotless/glue/scalafmt/ScalafmtFormatterFunc.java b/lib/src/scalafmt/java/com/diffplug/spotless/glue/scalafmt/ScalafmtFormatterFunc.java index 053bed0cab..6ed1dd2c16 100644 --- a/lib/src/scalafmt/java/com/diffplug/spotless/glue/scalafmt/ScalafmtFormatterFunc.java +++ b/lib/src/scalafmt/java/com/diffplug/spotless/glue/scalafmt/ScalafmtFormatterFunc.java @@ -52,8 +52,8 @@ public ScalafmtFormatterFunc(FileSignature configSignature) throws Exception { String scalafmtLibraryVersion = Versions.version(); if (!config.version().equals(scalafmtLibraryVersion)) { throw new IllegalArgumentException( - "Spotless is using " + scalafmtLibraryVersion + " but the config file declares " + config.version() + - ". Both must match. Update the version declared in the plugin's settings and/or the config file."); + "Spotless is using " + scalafmtLibraryVersion + " but the config file declares " + config.version() + + ". Both must match. Update the version declared in the plugin's settings and/or the config file."); } } diff --git a/lib/src/test/java/com/diffplug/spotless/JarStateTest.java b/lib/src/test/java/com/diffplug/spotless/JarStateTest.java index f44aa4a0b3..8b3d84fc18 100644 --- a/lib/src/test/java/com/diffplug/spotless/JarStateTest.java +++ b/lib/src/test/java/com/diffplug/spotless/JarStateTest.java @@ -15,13 +15,16 @@ */ package com.diffplug.spotless; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; +import java.nio.file.Path; import java.util.stream.Collectors; import org.assertj.core.api.SoftAssertions; @@ -33,7 +36,7 @@ class JarStateTest { @TempDir - java.nio.file.Path tempDir; + Path tempDir; File a; @@ -68,7 +71,7 @@ void itCreatesClassloaderWhenForcedClassLoaderNotSet() throws IOException { @Test void itReturnsForcedClassloaderIfSetNoMatterIfSetBeforeOrAfterCreation() throws IOException { JarState stateA = JarState.from(a.getName(), provisioner); - ClassLoader forcedClassLoader = new URLClassLoader(new java.net.URL[0]); + ClassLoader forcedClassLoader = new URLClassLoader(new URL[0]); JarState.setForcedClassLoader(forcedClassLoader); JarState stateB = JarState.from(b.getName(), provisioner); @@ -81,7 +84,7 @@ void itReturnsForcedClassloaderIfSetNoMatterIfSetBeforeOrAfterCreation() throws @Test void itReturnsForcedClassloaderEvenWhenRountripSerialized() throws IOException, ClassNotFoundException { JarState stateA = JarState.from(a.getName(), provisioner); - ClassLoader forcedClassLoader = new URLClassLoader(new java.net.URL[0]); + ClassLoader forcedClassLoader = new URLClassLoader(new URL[0]); JarState.setForcedClassLoader(forcedClassLoader); JarState stateB = JarState.from(b.getName(), provisioner); @@ -99,7 +102,7 @@ private JarState roundtripSerialize(JarState state) throws IOException, ClassNot try (ObjectOutputStream oOut = new ObjectOutputStream(outputStream)) { oOut.writeObject(state); } - try (ObjectInputStream oIn = new ObjectInputStream(new java.io.ByteArrayInputStream(outputStream.toByteArray()))) { + try (ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(outputStream.toByteArray()))) { return (JarState) oIn.readObject(); } } diff --git a/lib/src/test/java/com/diffplug/spotless/RingBufferByteArrayOutputStreamTest.java b/lib/src/test/java/com/diffplug/spotless/RingBufferByteArrayOutputStreamTest.java index 94fa49dbc1..18427723f7 100644 --- a/lib/src/test/java/com/diffplug/spotless/RingBufferByteArrayOutputStreamTest.java +++ b/lib/src/test/java/com/diffplug/spotless/RingBufferByteArrayOutputStreamTest.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. diff --git a/lib/src/test/java/com/diffplug/spotless/npm/TimedLoggerTest.java b/lib/src/test/java/com/diffplug/spotless/npm/TimedLoggerTest.java index f08d4f1622..132afe362e 100644 --- a/lib/src/test/java/com/diffplug/spotless/npm/TimedLoggerTest.java +++ b/lib/src/test/java/com/diffplug/spotless/npm/TimedLoggerTest.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. diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/AJacksonGradleConfig.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/AJacksonGradleConfig.java index 2185f3693a..e0b789efa3 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/AJacksonGradleConfig.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/AJacksonGradleConfig.java @@ -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. @@ -29,7 +29,7 @@ public abstract class AJacksonGradleConfig { protected String version = JacksonJsonStep.defaultVersion(); // Make sure to call 'formatExtension.addStep(createStep());' in the extented constructors - public AJacksonGradleConfig(JacksonConfig jacksonConfig, FormatExtension formatExtension) { + protected AJacksonGradleConfig(JacksonConfig jacksonConfig, FormatExtension formatExtension) { this.formatExtension = formatExtension; this.jacksonConfig = jacksonConfig; diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseGroovyExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseGroovyExtension.java index 15e042962e..230445740b 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseGroovyExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseGroovyExtension.java @@ -54,7 +54,7 @@ public GrEclipseConfig greclipse(String version) { return new GrEclipseConfig(version, this); } - public static class GrEclipseConfig { + public static final class GrEclipseConfig { private final EquoBasedStepBuilder builder; private final FormatExtension extension; diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseKotlinExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseKotlinExtension.java index 8d9a36c804..975be992c2 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseKotlinExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/BaseKotlinExtension.java @@ -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. @@ -71,7 +71,7 @@ public KtfmtConfig ktfmt(String version) { protected abstract boolean isScript(); - public class DiktatConfig { + public final class DiktatConfig { private final String version; private FileSignature config; @@ -97,7 +97,7 @@ private FormatterStep createStep() { } } - public class KtfmtConfig { + public final class KtfmtConfig { private final String version; private final ConfigurableStyle configurableStyle = new ConfigurableStyle(); private KtfmtStep.Style style; @@ -149,7 +149,7 @@ public void configure(Consumer optionsConfigur } } - public class KtlintConfig { + public final class KtlintConfig { private final String version; private FileSignature editorConfigPath; private Map editorConfigOverride; 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 cf9fa7cf83..777223c5f7 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 @@ -21,6 +21,9 @@ import static java.util.Objects.requireNonNull; import java.io.File; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.charset.Charset; import java.nio.file.Files; @@ -214,19 +217,15 @@ public void encoding(String charset) { } /** The files to be formatted = (target - targetExclude). */ - protected FileCollection target, targetExclude; + protected FileCollection target; + protected FileCollection targetExclude; /** The value from which files will be excluded if their content contain it. */ - @Nullable protected String targetExcludeContentPattern = null; + @Nullable protected String targetExcludeContentPattern; protected boolean isLicenseHeaderStep(FormatterStep formatterStep) { String formatterStepName = formatterStep.getName(); - - if (formatterStepName.startsWith(LicenseHeaderStep.class.getName())) { - return true; - } - - return false; + return formatterStepName.startsWith(LicenseHeaderStep.class.getName()); } /** @@ -378,7 +377,7 @@ public void addStep(Function createStepFn) { * step exists. */ protected int getExistingStepIdx(String stepName) { - for (int i = 0; i < steps.size(); ++i) { + for (int i = 0; i < steps.size(); i++) { if (steps.get(i).getName().equals(stepName)) { return i; } @@ -455,11 +454,11 @@ public String apply(String unixNewlines) { return closure.call(unixNewlines); } - private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { + private void writeObject(ObjectOutputStream stream) throws IOException { stream.writeObject(closure.dehydrate()); } - private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { this.closure = (Closure) stream.readObject(); } } @@ -566,7 +565,7 @@ public void nativeCmd(String name, String pathToExe, List arguments) { */ public class LicenseHeaderConfig { LicenseHeaderStep builder; - Boolean updateYearWithLatest = null; + Boolean updateYearWithLatest; public LicenseHeaderConfig named(String name) { String existingStepName = builder.getName(); @@ -686,7 +685,7 @@ public abstract static class NpmStepConfig> { private Consumer replaceStep; - public NpmStepConfig(Project project, Consumer replaceStep) { + protected NpmStepConfig(Project project, Consumer replaceStep) { this.project = requireNonNull(project); this.replaceStep = requireNonNull(replaceStep); } @@ -1137,12 +1136,11 @@ public TaskProvider createIndependentApplyTaskLazy(String taskNam task.mustRunAfter(BasePlugin.CLEAN_TASK_NAME); }); // create the apply task - TaskProvider applyTask = spotless.project.getTasks().register(taskName, SpotlessApply.class, + return spotless.project.getTasks().register(taskName, SpotlessApply.class, task -> { task.dependsOn(spotlessTask); task.init(spotlessTask.get()); }); - return applyTask; } protected GradleException noDefaultTargetException() { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GradleProvisioner.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GradleProvisioner.java index dbe9625c38..d6b6369bf8 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 @@ -38,7 +38,7 @@ import com.diffplug.spotless.Provisioner; /** Should be package-private. */ -class GradleProvisioner { +final class GradleProvisioner { private GradleProvisioner() {} enum Policy { @@ -135,8 +135,8 @@ private static Provisioner forConfigurationContainer(Project project, Configurat projName = projName + "/"; } throw new GradleException(String.format( - "You need to add a repository containing the '%s' artifact in '%sbuild.gradle'.%n" + - "E.g.: 'repositories { mavenCentral() }'", + "You need to add a repository containing the '%s' artifact in '%sbuild.gradle'.%n" + + "E.g.: 'repositories { mavenCentral() }'", mavenCoords, projName), e); } }; diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GroovyExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GroovyExtension.java index 3c5c4f3df2..127b9b1901 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GroovyExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GroovyExtension.java @@ -24,7 +24,7 @@ import com.diffplug.spotless.generic.LicenseHeaderStep; public class GroovyExtension extends BaseGroovyExtension implements HasBuiltinDelimiterForLicense, JvmLang { - private boolean excludeJava = false; + private boolean excludeJava; static final String NAME = "groovy"; @Inject @@ -62,9 +62,7 @@ protected void setupTask(SpotlessTask task) { } target = getSources(getProject(), message, - sourceSet -> { - return sourceSet.getExtensions().getByType(GroovySourceDirectorySet.class); - }, + sourceSet -> sourceSet.getExtensions().getByType(GroovySourceDirectorySet.class), file -> { final String name = file.getName(); if (excludeJava) { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/IdeHook.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/IdeHook.java index 6fe6b52a80..ffa1a18efb 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/IdeHook.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/IdeHook.java @@ -29,7 +29,7 @@ import com.diffplug.spotless.Formatter; import com.diffplug.spotless.NoLambda; -class IdeHook { +final class IdeHook { static class State extends NoLambda.EqualityBasedOnSerialization { final @Nullable String path; final boolean useStdIn; @@ -99,4 +99,6 @@ static void performHook(SpotlessTaskImpl spotlessTask, IdeHook.State state) { } } } + + private IdeHook() {} } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java index 09b7df6ebf..e76e1e8350 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java @@ -76,8 +76,8 @@ public class ImportOrderConfig { final String[] importOrder; final File importOrderFile; - boolean wildcardsLast = false; - boolean semanticSort = false; + boolean wildcardsLast; + boolean semanticSort; Set treatAsPackage = Set.of(); Set treatAsClass = Set.of(); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavascriptExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavascriptExtension.java index 894d18017c..399d8f718c 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavascriptExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavascriptExtension.java @@ -62,11 +62,11 @@ public abstract static class EslintBaseConfig> extends NpmStepConfig> { Map devDependencies = new LinkedHashMap<>(); - @Nullable Object configFilePath = null; + @Nullable Object configFilePath; - @Nullable String configJs = null; + @Nullable String configJs; - public EslintBaseConfig(Project project, Consumer replaceStep, + protected EslintBaseConfig(Project project, Consumer replaceStep, Map devDependencies) { super(project, replaceStep); this.devDependencies.putAll(requireNonNull(devDependencies)); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SerializableMisc.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SerializableMisc.java index c4ffbc4837..0cc197740f 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SerializableMisc.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SerializableMisc.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import com.diffplug.common.base.Preconditions; import com.diffplug.common.io.Files; -class SerializableMisc { +final class SerializableMisc { static void toFile(Serializable obj, File file) { try { java.nio.file.Files.createDirectories(file.getParentFile().toPath()); @@ -65,4 +65,6 @@ static T fromStream(Class clazz, InputStream stream) { throw Errors.asRuntime(e); } } + + private SerializableMisc() {} } 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 8ef7394c7b..a029bd00d4 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 @@ -57,7 +57,7 @@ public void performAction() throws IOException { // the file is misbehaved, so we'll write all its steps to DIAGNOSE_DIR Path relative = srcRoot.relativize(file.toPath()); Path diagnoseFile = diagnoseRoot.resolve(relative); - for (int i = 0; i < padded.steps().size(); ++i) { + for (int i = 0; i < padded.steps().size(); i++) { Path path = Path.of(diagnoseFile + "." + padded.type().name().toLowerCase(Locale.ROOT) + i); Files.createDirectories(path.getParent()); String version = padded.steps().get(i); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtension.java index 92079d67c4..2ff4896d9e 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtension.java @@ -280,8 +280,8 @@ protected final T maybeCreate(String name, Class FormatExtension existing = formats.get(name); if (existing != null) { if (!clazz.isInstance(existing)) { - throw new GradleException("Tried to add format named '" + name + "'" + - " of type " + clazz + " but one has already been created of type " + existing.getClass()); + throw new GradleException("Tried to add format named '" + name + "'" + + " of type " + clazz + " but one has already been created of type " + existing.getClass()); } else { return (T) existing; } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionImpl.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionImpl.java index 2e4e7f1202..d252491cbb 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionImpl.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionImpl.java @@ -23,7 +23,10 @@ import org.gradle.api.tasks.TaskProvider; public class SpotlessExtensionImpl extends SpotlessExtension { - final TaskProvider rootCheckTask, rootApplyTask, rootDiagnoseTask, rootInstallPreHook; + final TaskProvider rootCheckTask; + final TaskProvider rootApplyTask; + final TaskProvider rootDiagnoseTask; + final TaskProvider rootInstallPreHook; public SpotlessExtensionImpl(Project project) { super(project); @@ -35,9 +38,7 @@ public SpotlessExtensionImpl(Project project) { task.setGroup(TASK_GROUP); task.setDescription(APPLY_DESCRIPTION); }); - rootDiagnoseTask = project.getTasks().register(EXTENSION + DIAGNOSE, task -> { - task.setGroup(TASK_GROUP); // no description on purpose - }); + rootDiagnoseTask = project.getTasks().register(EXTENSION + DIAGNOSE, task -> task.setGroup(TASK_GROUP)); rootInstallPreHook = project.getTasks().register(EXTENSION + INSTALL_GIT_PRE_PUSH_HOOK, SpotlessInstallPrePushHookTask.class, task -> { task.setGroup(BUILD_SETUP_TASK_GROUP); task.setDescription(INSTALL_GIT_PRE_PUSH_HOOK_DESCRIPTION); @@ -66,16 +67,14 @@ protected void createFormatTasks(String name, FormatExtension formatExtension) { // clean removes the SpotlessCache, so we have to run after clean task.mustRunAfter(BasePlugin.CLEAN_TASK_NAME); }); - project.afterEvaluate(unused -> { - spotlessTask.configure(task -> { - // now that the task is being configured, we execute our actions - for (Action lazyAction : formatExtension.lazyActions) { - lazyAction.execute(formatExtension); - } - // and now we'll setup the task - formatExtension.setupTask(task); - }); - }); + project.afterEvaluate(unused -> spotlessTask.configure(task -> { + // now that the task is being configured, we execute our actions + for (Action lazyAction : formatExtension.lazyActions) { + lazyAction.execute(formatExtension); + } + // and now we'll setup the task + formatExtension.setupTask(task); + })); // create the check and apply control tasks TaskProvider applyTask = tasks.register(taskName + APPLY, SpotlessApply.class, task -> { @@ -84,9 +83,7 @@ protected void createFormatTasks(String name, FormatExtension formatExtension) { task.setEnabled(ideHook.path == null); task.dependsOn(spotlessTask); }); - rootApplyTask.configure(task -> { - task.dependsOn(ideHook.path == null ? applyTask : spotlessTask); - }); + rootApplyTask.configure(task -> task.dependsOn(ideHook.path == null ? applyTask : spotlessTask)); TaskProvider checkTask = tasks.register(taskName + CHECK, SpotlessCheck.class, task -> { SpotlessTaskImpl source = spotlessTask.get(); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionPredeclare.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionPredeclare.java index ae6243f53a..8c5a36cdc9 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionPredeclare.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionPredeclare.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2022 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,16 +29,14 @@ public class SpotlessExtensionPredeclare extends SpotlessExtension { public SpotlessExtensionPredeclare(Project project, GradleProvisioner.Policy policy) { super(project); getRegisterDependenciesTask().getTaskService().get().predeclaredProvisioner = policy.dedupingProvisioner(project); - project.afterEvaluate(unused -> { - toSetup.forEach((name, formatExtension) -> { - for (Action lazyAction : formatExtension.lazyActions) { - lazyAction.execute(formatExtension); - } - getRegisterDependenciesTask().steps.addAll(formatExtension.steps); - // needed to fix Deemon memory leaks (#1194), but this line came from https://github.com/diffplug/spotless/pull/1206 - LazyForwardingEquality.unlazy(getRegisterDependenciesTask().steps); - }); - }); + project.afterEvaluate(unused -> toSetup.forEach((name, formatExtension) -> { + for (Action lazyAction : formatExtension.lazyActions) { + lazyAction.execute(formatExtension); + } + getRegisterDependenciesTask().steps.addAll(formatExtension.steps); + // needed to fix Deemon memory leaks (#1194), but this line came from https://github.com/diffplug/spotless/pull/1206 + LazyForwardingEquality.unlazy(getRegisterDependenciesTask().steps); + })); } @Override diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskService.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTaskService.java index f1d78c57a9..33347f8dfc 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 @@ -185,7 +185,7 @@ public void visitFile(FileVisitDetails fileVisitDetails) { } }); StringBuilder builder = new StringBuilder(); - builder.append("There were " + total.get() + " lint error(s), they must be fixed or suppressed.\n"); + builder.append("There were ").append(total.get()).append(" lint error(s), they must be fixed or suppressed.\n"); for (Map.Entry>> lintsPerFile : allLints.entrySet()) { for (Map.Entry> stepLints : lintsPerFile.getValue().entrySet()) { String stepName = stepLints.getKey(); diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java index af9955aecb..b2b7826570 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java @@ -74,7 +74,7 @@ public class TypescriptFormatExtension extends NpmStepConfig devDependencies; @@ -196,7 +196,7 @@ public TypescriptEslintConfig eslint(Map devDependencies) { public class TypescriptEslintConfig extends EslintBaseConfig { - @Nullable Object typescriptConfigFilePath = null; + @Nullable Object typescriptConfigFilePath; public TypescriptEslintConfig(Map devDependencies) { super(getProject(), TypescriptExtension.this::replaceStep, devDependencies); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/BumpThisNumberIfACustomStepChangesTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/BumpThisNumberIfACustomStepChangesTest.java index 25ed3cab8b..016b85e9e0 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/BumpThisNumberIfACustomStepChangesTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/BumpThisNumberIfACustomStepChangesTest.java @@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test; abstract class BumpThisNumberIfACustomStepChangesTest extends GradleIntegrationHarness { - private boolean useConfigCache; + private final boolean useConfigCache; BumpThisNumberIfACustomStepChangesTest(boolean useConfigCache) { this.useConfigCache = useConfigCache; diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java index ac84424eb6..a942d6a9e8 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java @@ -184,7 +184,7 @@ void multipleFiles() throws Exception { @Test void manyFiles() throws Exception { List testFiles = new ArrayList<>(); - for (int i = 0; i < 9 + DiffMessageFormatter.MAX_FILES_TO_LIST - 1; ++i) { + for (int i = 0; i < 9 + DiffMessageFormatter.MAX_FILES_TO_LIST - 1; i++) { String fileName = "%02d".formatted(i) + ".txt"; testFiles.add(setFile(fileName).toContent("1\r\n2\r\n")); } @@ -258,7 +258,7 @@ void manyFiles() throws Exception { @Test void manyManyFiles() throws Exception { List testFiles = new ArrayList<>(); - for (int i = 0; i < 9 + DiffMessageFormatter.MAX_FILES_TO_LIST; ++i) { + for (int i = 0; i < 9 + DiffMessageFormatter.MAX_FILES_TO_LIST; i++) { String fileName = "%02d".formatted(i) + ".txt"; testFiles.add(setFile(fileName).toContent("1\r\n2\r\n")); } @@ -323,7 +323,7 @@ void manyManyFiles() throws Exception { @Test void longFile() throws Exception { StringBuilder builder = new StringBuilder(); - for (int i = 0; i < 1000; ++i) { + for (int i = 0; i < 1000; i++) { builder.append(i); builder.append("\r\n"); } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationHarness.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationHarness.java index 9e1738a02e..9a56920200 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationHarness.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationHarness.java @@ -147,9 +147,7 @@ public String getContents(Predicate subpathsToInclude) { /** Dumps the filtered file listing of the folder to the console. */ public String listFiles(Predicate subpathsToInclude) { - return StringPrinter.buildString(printer -> iterateFiles(subpathsToInclude, (subPath, file) -> { - printer.println(subPath + " [" + getFileAttributes(file) + "]"); - })); + return StringPrinter.buildString(printer -> iterateFiles(subpathsToInclude, (subPath, file) -> printer.println(subPath + " [" + getFileAttributes(file) + "]"))); } /** Dumps the file listing of the folder to the console. */ diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyExtensionTest.java index 7f87d8793c..8815ff87d7 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyExtensionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package com.diffplug.gradle.spotless; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IdeHookTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IdeHookTest.java index c38484384f..da2cf86440 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IdeHookTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IdeHookTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,12 @@ @TestInstance(TestInstance.Lifecycle.PER_CLASS) class IdeHookTest extends GradleIntegrationHarness { - private String output, error; - private File dirty, clean, diverge, outofbounds; + private String output; + private String error; + private File dirty; + private File clean; + private File diverge; + private File outofbounds; @BeforeEach void before() throws IOException { @@ -70,7 +74,7 @@ private void runWith(boolean configurationCache, String... arguments) throws IOE StringBuilder output = new StringBuilder(); StringBuilder error = new StringBuilder(); try (Writer outputWriter = new StringPrinter(output::append).toWriter(); - Writer errorWriter = new StringPrinter(error::append).toWriter();) { + Writer errorWriter = new StringPrinter(error::append).toWriter()) { gradleRunner(configurationCache) .withArguments(arguments) .forwardStdOutput(outputWriter) diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IndentIntegrationTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IndentIntegrationTest.java index fc883b41e9..38457faae9 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IndentIntegrationTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/IndentIntegrationTest.java @@ -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. @@ -83,8 +83,7 @@ private BuildResult runIndentFormatter(String indentationMethodName, String reso " }", "}"); setFile("test.txt").toResource(resourceFile); - BuildResult result = gradleRunner().withArguments("spotlessApply").build(); - return result; + return gradleRunner().withArguments("spotlessApply").build(); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/MultiProjectTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/MultiProjectTest.java index 5d184e15e5..69301327c7 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/MultiProjectTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/MultiProjectTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-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. @@ -23,14 +23,14 @@ import com.diffplug.common.base.StringPrinter; class MultiProjectTest extends GradleIntegrationHarness { - private static int N = 100; + private static final int N = 100; private void createNSubprojects() throws IOException { - for (int i = 0; i < N; ++i) { + for (int i = 0; i < N; i++) { createSubproject(Integer.toString(i)); } String settings = StringPrinter.buildString(printer -> { - for (int i = 0; i < N; ++i) { + for (int i = 0; i < N; i++) { printer.println("include '" + i + "'"); } }); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java index b6547204b8..9b6edf526a 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java @@ -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. @@ -52,13 +52,10 @@ void useInlineConfig(String prettierVersion) throws IOException { setFile("test.ts").toResource("npm/prettier/config/typescript.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); - switch (prettierVersion) { - case PRETTIER_VERSION_2: + if (PRETTIER_VERSION_2.equals(prettierVersion)) { assertFile("test.ts").sameAsResource("npm/prettier/config/typescript.configfile_prettier_2.clean"); - break; - case PRETTIER_VERSION_3: + } else if (PRETTIER_VERSION_3.equals(prettierVersion)) { assertFile("test.ts").sameAsResource("npm/prettier/config/typescript.configfile_prettier_3.clean"); - break; } } @@ -105,13 +102,10 @@ void useFileConfig(String prettierVersion) throws IOException { setFile("test.ts").toResource("npm/prettier/config/typescript.dirty"); final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); - switch (prettierVersion) { - case PRETTIER_VERSION_2: + if (PRETTIER_VERSION_2.equals(prettierVersion)) { assertFile("test.ts").sameAsResource("npm/prettier/config/typescript.configfile_prettier_2.clean"); - break; - case PRETTIER_VERSION_3: + } else if (PRETTIER_VERSION_3.equals(prettierVersion)) { assertFile("test.ts").sameAsResource("npm/prettier/config/typescript.configfile_prettier_3.clean"); - break; } } @@ -140,14 +134,11 @@ void chooseParserBasedOnFilename(String prettierVersion) throws IOException { void useJavaCommunityPlugin(String prettierVersion) throws IOException { var prettierPluginJava = ""; var prettierConfigPluginsStr = ""; - switch (prettierVersion) { - case PRETTIER_VERSION_2: - prettierPluginJava = "2.1.0"; // last version to support v2 - break; - case PRETTIER_VERSION_3: + if (PRETTIER_VERSION_2.equals(prettierVersion)) { + prettierPluginJava = "2.1.0"; + } else if (PRETTIER_VERSION_3.equals(prettierVersion)) { prettierPluginJava = "2.3.0"; // latest to support v3 prettierConfigPluginsStr = "prettierConfig['plugins'] = ['prettier-plugin-java']"; - break; } setFile("build.gradle").toLines( "plugins {", @@ -177,13 +168,10 @@ void useJavaCommunityPlugin(String prettierVersion) throws IOException { @ValueSource(strings = {PRETTIER_VERSION_2, PRETTIER_VERSION_3}) void useJavaCommunityPluginFileConfig(String prettierVersion) throws IOException { var prettierPluginJava = ""; - switch (prettierVersion) { - case PRETTIER_VERSION_2: - prettierPluginJava = "2.1.0"; // last version to support v2 - break; - case PRETTIER_VERSION_3: - prettierPluginJava = "2.3.0"; // latest to support v3 - break; + if (PRETTIER_VERSION_2.equals(prettierVersion)) { + prettierPluginJava = "2.1.0"; + } else if (PRETTIER_VERSION_3.equals(prettierVersion)) { + prettierPluginJava = "2.3.0"; } setFile(".prettierrc.yml").toResource("npm/prettier/config/.prettierrc_java_plugin.yml"); setFile("build.gradle").toLines( @@ -235,14 +223,11 @@ void suggestsMissingJavaCommunityPlugin(String prettierVersion) throws IOExcepti void usePhpCommunityPlugin(String prettierVersion) throws IOException { var prettierPluginPhp = ""; var prettierConfigPluginsStr = ""; - switch (prettierVersion) { - case PRETTIER_VERSION_2: - prettierPluginPhp = "0.19.7"; // last version to support v2 - break; - case PRETTIER_VERSION_3: + if (PRETTIER_VERSION_2.equals(prettierVersion)) { + prettierPluginPhp = "0.19.7"; + } else if (PRETTIER_VERSION_3.equals(prettierVersion)) { prettierPluginPhp = "0.20.1"; // latest to support v3 prettierConfigPluginsStr = "prettierConfig['plugins'] = ['@prettier/plugin-php']"; - break; } setFile("build.gradle").toLines( "plugins {", @@ -280,17 +265,14 @@ void usePhpAndJavaCommunityPlugin(String prettierVersion) throws IOException { var prettierPluginPhp = ""; var prettierConfigPluginsJavaStr = ""; var prettierConfigPluginsPhpStr = ""; - switch (prettierVersion) { - case PRETTIER_VERSION_2: + if (PRETTIER_VERSION_2.equals(prettierVersion)) { prettierPluginJava = "2.1.0"; // last version to support v2 - prettierPluginPhp = "0.19.7"; // last version to support v2 - break; - case PRETTIER_VERSION_3: + prettierPluginPhp = "0.19.7"; + } else if (PRETTIER_VERSION_3.equals(prettierVersion)) { prettierPluginJava = "2.3.0"; // latest to support v3 prettierPluginPhp = "0.20.1"; // latest to support v3 prettierConfigPluginsJavaStr = "prettierConfigJava['plugins'] = ['prettier-plugin-java']"; prettierConfigPluginsPhpStr = "prettierConfigPhp['plugins'] = ['@prettier/plugin-php']"; - break; } setFile("build.gradle").toLines( "plugins {", diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ToggleOffOnTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ToggleOffOnTest.java index 11850a5cff..c1bb90dd6d 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ToggleOffOnTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ToggleOffOnTest.java @@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test; abstract class ToggleOffOnTest extends GradleIntegrationHarness { - private boolean useConfigCache; + private final boolean useConfigCache; ToggleOffOnTest(boolean useConfigCache) { this.useConfigCache = useConfigCache; diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ArtifactResolver.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ArtifactResolver.java index 35c8e6d421..10fc03d9b3 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ArtifactResolver.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ArtifactResolver.java @@ -61,7 +61,7 @@ public ArtifactResolver(RepositorySystem repositorySystem, RepositorySystemSessi * of the specified coordinates and optionally their transitive dependencies. */ public Set resolve(boolean withTransitives, Collection mavenCoordinates) { - Collection excludeTransitive = new ArrayList(1); + Collection excludeTransitive = new ArrayList<>(1); if (!withTransitives) { excludeTransitive.add(EXCLUDE_ALL_TRANSITIVES); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FileLocator.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FileLocator.java index 09938e8ee6..3781d404be 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FileLocator.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FileLocator.java @@ -37,7 +37,9 @@ public class FileLocator { static final String TMP_RESOURCE_FILE_PREFIX = "spotless-resource-"; private final ResourceManager resourceManager; - private final File baseDir, buildDir, dataDir; + private final File baseDir; + private final File buildDir; + private final File dataDir; public FileLocator(ResourceManager resourceManager, File baseDir, File buildDir) { this.resourceManager = Objects.requireNonNull(resourceManager); diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java index 980bd1751a..6c7cc0d349 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java @@ -96,7 +96,7 @@ public final Formatter newFormatter(Supplier> filesToFormat, Form List formatterSteps = factories.stream() .filter(Objects::nonNull) // all unrecognized steps from XML config appear as nulls in the list .map(factory -> factory.newFormatterStep(stepConfig)) - .collect(Collectors.toCollection(() -> new ArrayList())); + .collect(Collectors.toCollection(ArrayList::new)); if (toggle != null) { List formatterStepsBeforeToggle = formatterSteps; formatterSteps = List.of(toggle.createFence().preserveWithin(formatterStepsBeforeToggle)); diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/IdeHook.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/IdeHook.java index 6b7750c060..5604376dca 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/IdeHook.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/IdeHook.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. @@ -24,7 +24,7 @@ import com.diffplug.spotless.DirtyState; import com.diffplug.spotless.Formatter; -class IdeHook { +final class IdeHook { private static void dumpIsClean() { System.err.println("IS CLEAN"); @@ -80,4 +80,6 @@ private static boolean projectContainsFile(Iterable projectFiles, File fil } return false; } + + private IdeHook() {} } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java index 60eb8af762..bc95bdc6ff 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.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. @@ -19,9 +19,9 @@ * Tracks the number of processed files, typically by a single Formatter for a whole repository */ class ImpactedFilesTracker { - protected int nbskippedAsCleanCache = 0; - protected int nbCheckedButAlreadyClean = 0; - protected int nbCleaned = 0; + protected int nbskippedAsCleanCache; + protected int nbCheckedButAlreadyClean; + protected int nbCleaned; /** * Some cache mechanism may indicate some content is clean, without having to execute the cleaning process diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/MavenProvisioner.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/MavenProvisioner.java index 2ce571a09d..ad4ecd49cf 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/MavenProvisioner.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/MavenProvisioner.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. @@ -18,7 +18,7 @@ import com.diffplug.spotless.Provisioner; /** Maven integration for Provisioner. */ -public class MavenProvisioner { +public final class MavenProvisioner { private MavenProvisioner() {} public static Provisioner create(ArtifactResolver artifactResolver) { diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java index f677979b6f..9d00699816 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java @@ -25,6 +25,7 @@ import org.apache.maven.plugins.annotations.Parameter; import com.diffplug.spotless.Formatter; +import com.diffplug.spotless.Lint; import com.diffplug.spotless.LintState; import com.diffplug.spotless.LintSuppression; import com.diffplug.spotless.maven.incremental.UpToDateChecker; @@ -85,9 +86,9 @@ protected void process(String name, Iterable files, Formatter formatter, U message.append("There were ").append(lintCount).append(" lint error(s), they must be fixed or suppressed."); // Build lint messages in Gradle format (using relative path, not just filename) - for (Map.Entry> stepEntry : lintState.getLintsByStep(formatter).entrySet()) { + for (Map.Entry> stepEntry : lintState.getLintsByStep(formatter).entrySet()) { String stepName = stepEntry.getKey(); - for (com.diffplug.spotless.Lint lint : stepEntry.getValue()) { + for (Lint lint : stepEntry.getValue()) { String relativePath = LintSuppression.relativizeAsUnix(baseDir, file); message.append("\n ").append(relativePath).append(":"); lint.addWarningMessageTo(message, stepName, true); diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java index 8081a0d029..2a8955aec1 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java @@ -40,7 +40,7 @@ import jakarta.annotation.Nullable; -class FileIndex { +final class FileIndex { private static final String SEPARATOR = " "; diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/NoopChecker.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/NoopChecker.java index 8d57c0be4a..9c3351e2e6 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/NoopChecker.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/NoopChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2022 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. @@ -20,7 +20,7 @@ import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; -class NoopChecker implements UpToDateChecker { +final class NoopChecker implements UpToDateChecker { private NoopChecker() {} diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/ObjectDigestOutputStream.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/ObjectDigestOutputStream.java index 8ff2c03c9f..62ab097c22 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/ObjectDigestOutputStream.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/ObjectDigestOutputStream.java @@ -1,5 +1,5 @@ /* - * Copyright 2021 DiffPlug + * Copyright 2021-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -class ObjectDigestOutputStream extends ObjectOutputStream { +final class ObjectDigestOutputStream extends ObjectOutputStream { private final MessageDigest messageDigest; diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/PluginFingerprint.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/PluginFingerprint.java index 34a01e235a..03ea1812d3 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/PluginFingerprint.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/PluginFingerprint.java @@ -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. @@ -33,7 +33,7 @@ *
  • Formatter instances created according to the POM configuration
  • * */ -class PluginFingerprint { +final class PluginFingerprint { private static final String SPOTLESS_PLUGIN_KEY = "com.diffplug.spotless:spotless-maven-plugin"; diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/ImportOrder.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/ImportOrder.java index 88f47a2a64..5fecb322e7 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/ImportOrder.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/ImportOrder.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. @@ -34,7 +34,7 @@ public class ImportOrder implements FormatterStepFactory { private String order; @Parameter - private boolean wildcardsLast = false; + private boolean wildcardsLast; /** * Whether imports should be sorted based on semantics (i.e. sorted by package, @@ -44,7 +44,7 @@ public class ImportOrder implements FormatterStepFactory { * lexicographically. */ @Parameter - private boolean semanticSort = false; + private boolean semanticSort; /** * The prefixes that should be treated as packages for diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Gson.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Gson.java index a76ddd396e..e29f0b4003 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Gson.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Gson.java @@ -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. @@ -28,10 +28,10 @@ public class Gson implements FormatterStepFactory { int indentSpaces = Json.DEFAULT_INDENTATION; @Parameter - boolean sortByKeys = false; + boolean sortByKeys; @Parameter - boolean escapeHtml = false; + boolean escapeHtml; @Parameter String version = GsonStep.DEFAULT_VERSION; diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java index fbf920b853..03dd87e898 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/npm/AbstractNpmFormatterStepFactory.java @@ -49,18 +49,15 @@ public abstract class AbstractNpmFormatterStepFactory implements FormatterStepFa private String npmInstallCache; protected File npm(FormatterStepConfig stepConfig) { - File npm = npmExecutable != null ? stepConfig.getFileLocator().locateFile(npmExecutable) : null; - return npm; + return npmExecutable != null ? stepConfig.getFileLocator().locateFile(npmExecutable) : null; } protected File node(FormatterStepConfig stepConfig) { - File node = nodeExecutable != null ? stepConfig.getFileLocator().locateFile(nodeExecutable) : null; - return node; + return nodeExecutable != null ? stepConfig.getFileLocator().locateFile(nodeExecutable) : null; } protected File npmrc(FormatterStepConfig stepConfig) { - File npmrc = this.npmrc != null ? stepConfig.getFileLocator().locateFile(this.npmrc) : null; - return npmrc; + return this.npmrc != null ? stepConfig.getFileLocator().locateFile(this.npmrc) : null; } protected File buildDir(FormatterStepConfig stepConfig) { diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/IdeHookTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/IdeHookTest.java index 68820b2356..452efd4a26 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/IdeHookTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/IdeHookTest.java @@ -25,8 +25,12 @@ import com.diffplug.spotless.ProcessRunner; class IdeHookTest extends MavenIntegrationHarness { - private String output, error; - private File dirty, clean, diverge, outofbounds; + private String output; + private String error; + private File dirty; + private File clean; + private File diverge; + private File outofbounds; @BeforeEach void before() throws IOException { @@ -44,7 +48,6 @@ void before() throws IOException { dirty = setFile("DIRTY.md").toContent("World"); clean = setFile("CLEAN.md").toContent("Mars"); outofbounds = setFile("OUTOFBOUNDS.md").toContent("Mars"); - ; } private void runWith(String... arguments) throws IOException, InterruptedException { diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java index cd135605dc..3065840b83 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java @@ -33,6 +33,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterAll; @@ -93,12 +94,13 @@ void gitAttributes() throws IOException { if (Jvm.version() >= 16) { // for GJF https://github.com/diffplug/spotless/issues/834 setFile(".mvn/jvm.config").toContent( - "--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED" + - " --add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED" + - " --add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED" + - " --add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED" + - " --add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED" + + "--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED" + + " --add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED" + + " --add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED" + + " --add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED" + + " --add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED" // this last line is for Detekt + + // this last line is for Detekt " --add-opens java.base/java.lang=ALL-UNNAMED"); } // copy the mvnw resources @@ -359,7 +361,7 @@ protected static String[] formats(String[]... formats) { protected StringSelfie expectSelfieErrorMsg(ProcessRunner.Result result) { String concatenatedError = result.stdOutUtf8().lines() .map(line -> line.startsWith(ERROR_PREFIX) ? line.substring(ERROR_PREFIX.length()) : null) - .filter(line -> line != null) + .filter(Objects::nonNull) .collect(Collectors.joining("\n")); String sanitizedVersion = concatenatedError.replaceFirst("com\\.diffplug\\.spotless:spotless-maven-plugin:([^:]+):", "com.diffplug.spotless:spotless-maven-plugin:VERSION:"); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java index 06edf437fc..061f5e6989 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java @@ -33,7 +33,7 @@ * Harness for running a Maven build, same idea as the * GradleRunner from the Gradle testkit. */ -public class MavenRunner { +public final class MavenRunner { public static MavenRunner create() { return new MavenRunner(); } @@ -42,8 +42,8 @@ private MavenRunner() {} private File projectDir; private String[] args; - private Map environment = new HashMap<>(); - private Map systemProperties = new HashMap<>(); + private final Map environment = new HashMap<>(); + private final Map systemProperties = new HashMap<>(); private ProcessRunner runner; public MavenRunner withProjectDir(File projectDir) { diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultiModuleProjectTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultiModuleProjectTest.java index a2d491cb2b..108f9b1fe7 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultiModuleProjectTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultiModuleProjectTest.java @@ -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. @@ -177,7 +177,7 @@ private void createSubProjectFiles(String subProjectName, List s } } - static class SubProjectFile { + static final class SubProjectFile { private final String from; private final String to; diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpecificFilesTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpecificFilesTest.java index 1486fefa95..43d96945ec 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpecificFilesTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpecificFilesTest.java @@ -85,10 +85,11 @@ void multiFile() throws IOException, InterruptedException { @Test void regexp() throws IOException, InterruptedException { String pattern; - if (isOnWindows()) + if (isOnWindows()) { pattern = "\".*\\\\src\\\\main\\\\java\\\\test(1|3).java\""; - else + } else { pattern = "'.*/src/main/java/test(1|3).java'"; + } integration(pattern, true, false, true); } } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LineEndingsTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LineEndingsTest.java index 1c99234fcc..22c6734564 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LineEndingsTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LineEndingsTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,10 +51,10 @@ private void runTest(String sourceContent, String targetContent) throws Exceptio } private String getClassWithLineEndings(String lineEnding) { - return "public class Java {" + lineEnding + - " public static void main(String[] args) {" + lineEnding + - " System.out.println(\"hello\");" + lineEnding + - " }" + lineEnding + - "}"; + return "public class Java {" + lineEnding + + " public static void main(String[] args) {" + lineEnding + + " System.out.println(\"hello\");" + lineEnding + + " }" + lineEnding + + "}"; } } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/UpToDateCheckingTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/UpToDateCheckingTest.java index cfc17594ca..f3762ff5bb 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/UpToDateCheckingTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/UpToDateCheckingTest.java @@ -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. diff --git a/rewrite.yml b/rewrite.yml new file mode 100644 index 0000000000..f3edd8d212 --- /dev/null +++ b/rewrite.yml @@ -0,0 +1,49 @@ +--- +type: specs.openrewrite.org/v1beta/recipe +name: com.diffplug.spotless.openrewrite.SanityCheck +displayName: Apply all Java & Gradle best practices +description: Comprehensive code quality recipe combining modernization, security, and best practices. +tags: + - java + - gradle + - static-analysis + - cleanup +recipeList: + - org.openrewrite.gradle.GradleBestPractices + - org.openrewrite.java.RemoveUnusedImports + - org.openrewrite.java.format.RemoveTrailingWhitespace + - org.openrewrite.java.migrate.UpgradeToJava17 + - org.openrewrite.java.recipes.JavaRecipeBestPractices + - org.openrewrite.java.recipes.RecipeTestingBestPractices + - org.openrewrite.java.security.JavaSecurityBestPractices + - org.openrewrite.staticanalysis.CommonStaticAnalysis + - org.openrewrite.staticanalysis.EqualsAvoidsNull + - org.openrewrite.staticanalysis.JavaApiBestPractices + - org.openrewrite.staticanalysis.LowercasePackage + - org.openrewrite.staticanalysis.MissingOverrideAnnotation + - org.openrewrite.staticanalysis.ModifierOrder + - org.openrewrite.staticanalysis.NoFinalizer + - org.openrewrite.staticanalysis.NoToStringOnStringType + - org.openrewrite.staticanalysis.NoValueOfOnStringType + - org.openrewrite.staticanalysis.RemoveUnusedLocalVariables + - org.openrewrite.staticanalysis.RemoveUnusedPrivateFields + - org.openrewrite.staticanalysis.RemoveUnusedPrivateMethods + - org.openrewrite.staticanalysis.UnnecessaryCloseInTryWithResources + - org.openrewrite.staticanalysis.UnnecessaryExplicitTypeArguments + - org.openrewrite.staticanalysis.UnnecessaryParentheses + - org.openrewrite.staticanalysis.UnnecessaryReturnAsLastStatement + - tech.picnic.errorprone.refasterrules.BigDecimalRulesRecipes + - tech.picnic.errorprone.refasterrules.CharSequenceRulesRecipes + - tech.picnic.errorprone.refasterrules.ClassRulesRecipes + - tech.picnic.errorprone.refasterrules.CollectionRulesRecipes + - tech.picnic.errorprone.refasterrules.ComparatorRulesRecipes + - tech.picnic.errorprone.refasterrules.FileRulesRecipes + - tech.picnic.errorprone.refasterrules.MicrometerRulesRecipes + - tech.picnic.errorprone.refasterrules.PatternRulesRecipes + - tech.picnic.errorprone.refasterrules.PreconditionsRulesRecipes + - tech.picnic.errorprone.refasterrules.PrimitiveRulesRecipes + - tech.picnic.errorprone.refasterrules.StreamRulesRecipes + - tech.picnic.errorprone.refasterrules.TimeRulesRecipes + # - org.openrewrite.staticanalysis.CodeCleanup # bug https://github.com/openrewrite/rewrite/pull/6084 + # - org.openrewrite.staticanalysis.UnnecessaryThrows # bug +--- diff --git a/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java b/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java index 5f6b33289b..43744dbf74 100644 --- a/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java +++ b/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java @@ -178,7 +178,7 @@ public ReadAsserter assertFile(File file) { return new ReadAsserter(file); } - public static class ReadAsserter { + public static final class ReadAsserter { private final File file; private ReadAsserter(File file) { @@ -223,7 +223,7 @@ public WriteAsserter setFile(String path) { return new WriteAsserter(newFile(path)); } - public static class WriteAsserter { + public static final class WriteAsserter { private File file; private WriteAsserter(File file) { @@ -240,16 +240,12 @@ public File toContent(String content) { } public File toContent(String content, Charset charset) { - ThrowingEx.run(() -> { - Files.write(file.toPath(), content.getBytes(charset)); - }); + ThrowingEx.run(() -> Files.write(file.toPath(), content.getBytes(charset))); return file; } public File toResource(String path) { - ThrowingEx.run(() -> { - Files.write(file.toPath(), getTestResource(path).getBytes(StandardCharsets.UTF_8)); - }); + ThrowingEx.run(() -> Files.write(file.toPath(), getTestResource(path).getBytes(StandardCharsets.UTF_8))); return file; } diff --git a/testlib/src/main/java/com/diffplug/spotless/StepHarness.java b/testlib/src/main/java/com/diffplug/spotless/StepHarness.java index 5b5a28717b..feb451d1fb 100644 --- a/testlib/src/main/java/com/diffplug/spotless/StepHarness.java +++ b/testlib/src/main/java/com/diffplug/spotless/StepHarness.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package com.diffplug.spotless; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.nio.charset.StandardCharsets; @@ -25,7 +25,7 @@ import com.diffplug.selfie.StringSelfie; /** An api for testing a {@code FormatterStep} that doesn't depend on the File path. DO NOT ADD FILE SUPPORT TO THIS, use {@link StepHarnessWithFile} if you need that. */ -public class StepHarness extends StepHarnessBase { +public final class StepHarness extends StepHarnessBase { private StepHarness(Formatter formatter, RoundTrip roundTrip) { super(formatter, roundTrip); } diff --git a/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java b/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java index 519fe3037f..9f1658b9d1 100644 --- a/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java +++ b/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java @@ -15,7 +15,7 @@ */ package com.diffplug.spotless; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.IOException; @@ -26,7 +26,7 @@ import com.diffplug.selfie.StringSelfie; /** An api for testing a {@code FormatterStep} that depends on the File path. */ -public class StepHarnessWithFile extends StepHarnessBase { +public final class StepHarnessWithFile extends StepHarnessBase { private final ResourceHarness harness; private StepHarnessWithFile(ResourceHarness harness, Formatter formatter, RoundTrip roundTrip) { diff --git a/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java b/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java index 16a1a1439c..672dd8eba9 100644 --- a/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java +++ b/testlib/src/main/java/com/diffplug/spotless/TestProvisioner.java @@ -143,9 +143,7 @@ public static Provisioner mavenCentral() { return mavenCentral.get(); } - private static final Supplier mavenCentral = Suppliers.memoize(() -> { - return caching("mavenCentral", () -> createWithRepositories(repo -> repo.mavenCentral())); - }); + private static final Supplier mavenCentral = Suppliers.memoize(() -> caching("mavenCentral", () -> createWithRepositories(repo -> repo.mavenCentral()))); /** Creates a Provisioner for the local maven repo for development purpose. */ public static Provisioner mavenLocal() { @@ -159,9 +157,5 @@ public static Provisioner snapshots() { return snapshots.get(); } - private static final Supplier snapshots = () -> createWithRepositories(repo -> { - repo.maven(setup -> { - setup.setUrl("https://oss.sonatype.org/content/repositories/snapshots"); - }); - }); + private static final Supplier snapshots = () -> createWithRepositories(repo -> repo.maven(setup -> setup.setUrl("https://oss.sonatype.org/content/repositories/snapshots"))); } diff --git a/testlib/src/test/java/com/diffplug/spotless/JvmTest.java b/testlib/src/test/java/com/diffplug/spotless/JvmTest.java index 0057c814eb..746ea5d46a 100644 --- a/testlib/src/test/java/com/diffplug/spotless/JvmTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/JvmTest.java @@ -42,7 +42,7 @@ void initialize() { @Test void supportAdd() { - Integer differentVersions[] = {0, 1, 2}; + Integer[] differentVersions = {0, 1, 2}; Arrays.asList(differentVersions).forEach(v -> testSupport.add(v + Jvm.version(), v.toString())); Arrays.asList(differentVersions).forEach(v -> assertThat(testSupport.toString()).contains("Version %d".formatted(v))); assertThat(testSupport.toString()).contains("%s alternatives".formatted(TEST_NAME)); @@ -51,9 +51,7 @@ void supportAdd() { @ParameterizedTest(name = "{index} {1}") @MethodSource void supportAddFailsFor(Consumer> configuration, String nameNotUsed) { - assertThrows(IllegalArgumentException.class, () -> { - configuration.accept(testSupport); - }); + assertThrows(IllegalArgumentException.class, () -> configuration.accept(testSupport)); } private static Stream supportAddFailsFor() { @@ -76,11 +74,9 @@ void supportEmptyConfiguration() { testSupport.assertFormatterSupported("0.1"); Exception expected = new Exception("Some test exception"); - Exception actual = assertThrows(Exception.class, () -> { - testSupport.suggestLaterVersionOnError("0.0", unused -> { - throw expected; - }).apply(""); - }); + Exception actual = assertThrows(Exception.class, () -> testSupport.suggestLaterVersionOnError("0.0", unused -> { + throw expected; + }).apply("")); assertEquals(expected, actual); } @@ -94,34 +90,26 @@ void supportListsMinimumJvmIfOnlyHigherJvmSupported() { assertNull(testSupport.getRecommendedFormatterVersion(), "No formatter version is supported"); for (String fmtVersion : Arrays.asList("1.2", "1.2.3", "1.2-SNAPSHOT", "1.2.3-SNAPSHOT")) { - String proposal = assertThrows(Lint.ShortcutException.class, () -> { - testSupport.assertFormatterSupported(fmtVersion); - }).getLints().get(0).getDetail(); + String proposal = assertThrows(Lint.ShortcutException.class, () -> testSupport.assertFormatterSupported(fmtVersion)).getLints().get(0).getDetail(); assertThat(proposal).contains(String.format("on JVM %d", Jvm.version())); assertThat(proposal).contains("%s %s requires JVM %d+".formatted(TEST_NAME, fmtVersion, higherJvmVersion)); assertThat(proposal).contains("try %s alternatives".formatted(TEST_NAME)); - proposal = assertThrows(Exception.class, () -> { - testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { - throw testException; - }).apply(""); - }).getMessage(); + proposal = assertThrows(Exception.class, () -> testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { + throw testException; + }).apply("")).getMessage(); assertThat(proposal).contains(String.format("on JVM %d", Jvm.version())); assertThat(proposal).contains("%s %s requires JVM %d+".formatted(TEST_NAME, fmtVersion, higherJvmVersion)); assertThat(proposal).contains("try %s alternatives".formatted(TEST_NAME)); } for (String fmtVersion : Arrays.asList("1.2.4", "2", "1.2.5-SNAPSHOT")) { - String proposal = assertThrows(Lint.ShortcutException.class, () -> { - testSupport.assertFormatterSupported(fmtVersion); - }).getLints().get(0).getDetail(); + String proposal = assertThrows(Lint.ShortcutException.class, () -> testSupport.assertFormatterSupported(fmtVersion)).getLints().get(0).getDetail(); assertThat(proposal).contains("%s %s requires JVM %d+".formatted(TEST_NAME, fmtVersion, higherJvmVersion + 1)); - proposal = assertThrows(Exception.class, () -> { - testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { - throw testException; - }).apply(""); - }).getMessage(); + proposal = assertThrows(Exception.class, () -> testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { + throw testException; + }).apply("")).getMessage(); assertThat(proposal).contains("%s %s requires JVM %d+".formatted(TEST_NAME, fmtVersion, higherJvmVersion + 1)); } } @@ -135,11 +123,9 @@ void supportProposesFormatterUpgrade() { for (String fmtVersion : Arrays.asList("0", "1", "1.9", "1.9-SNAPSHOT")) { testSupport.assertFormatterSupported(fmtVersion); - String proposal = assertThrows(Exception.class, () -> { - testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { - throw new Exception("Some test exception"); - }).apply(""); - }).getMessage(); + String proposal = assertThrows(Exception.class, () -> testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { + throw new Exception("Some test exception"); + }).apply("")).getMessage(); assertThat(proposal.replace("\r", "")).isEqualTo("My Test Formatter " + fmtVersion + " is currently being used, but outdated.\n" + "My Test Formatter 2 is the recommended version, which may have fixed this problem.\n" + "My Test Formatter 2 requires JVM " + requiredJvm + "+."); @@ -153,11 +139,9 @@ void supportProposesJvmUpgrade() { testSupport.add(higherJvm, "2"); testSupport.add(higherJvm + 1, "3"); for (String fmtVersion : Arrays.asList("1", "1.0")) { - String proposal = assertThrows(Exception.class, () -> { - testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { - throw new Exception("Some test exception"); - }).apply(""); - }).getMessage(); + String proposal = assertThrows(Exception.class, () -> testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { + throw new Exception("Some test exception"); + }).apply("")).getMessage(); assertThat(proposal).contains(String.format("on JVM %d", Jvm.version())); assertThat(proposal).contains("limits you to %s %s".formatted(TEST_NAME, "1")); assertThat(proposal).contains("upgrade your JVM to %d+".formatted(higherJvm)); @@ -172,11 +156,9 @@ void supportAllowsExperimentalVersions() { testSupport.assertFormatterSupported(fmtVersion); Exception testException = new Exception("Some test exception"); - Exception exception = assertThrows(Exception.class, () -> { - testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { - throw testException; - }).apply(""); - }); + Exception exception = assertThrows(Exception.class, () -> testSupport.suggestLaterVersionOnError(fmtVersion, unused -> { + throw testException; + }).apply("")); assertEquals(testException, exception); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/generic/IdeaStepTest.java b/testlib/src/test/java/com/diffplug/spotless/generic/IdeaStepTest.java index 299ea4e45f..d7dbc8025a 100644 --- a/testlib/src/test/java/com/diffplug/spotless/generic/IdeaStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/generic/IdeaStepTest.java @@ -104,7 +104,7 @@ void configureFile() throws Exception { "formatting was applied to clean file"); } - private File buildDir = null; + private File buildDir; protected File buildDir() { if (this.buildDir == null) { diff --git a/testlib/src/test/java/com/diffplug/spotless/gherkin/GherkinUtilsStepTest.java b/testlib/src/test/java/com/diffplug/spotless/gherkin/GherkinUtilsStepTest.java index 05fdc019ad..c9ccf15fb1 100644 --- a/testlib/src/test/java/com/diffplug/spotless/gherkin/GherkinUtilsStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/gherkin/GherkinUtilsStepTest.java @@ -97,7 +97,7 @@ public void canSetIndentationLevelTo0() throws Exception { @Test public void equality() { new SerializableEqualityTester() { - int spaces = 0; + int spaces; @Override protected void setupTest(API api) { diff --git a/testlib/src/test/java/com/diffplug/spotless/java/GoogleJavaFormatStepTest.java b/testlib/src/test/java/com/diffplug/spotless/java/GoogleJavaFormatStepTest.java index 72e470cf05..e6e2fbdc76 100644 --- a/testlib/src/test/java/com/diffplug/spotless/java/GoogleJavaFormatStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/java/GoogleJavaFormatStepTest.java @@ -138,7 +138,7 @@ void equality() throws Exception { new SerializableEqualityTester() { String version = "1.10.0"; String style = ""; - boolean reflowLongStrings = false; + boolean reflowLongStrings; @Override protected void setupTest(API api) { @@ -170,7 +170,7 @@ void equalityGroupArtifact() throws Exception { String groupArtifact = GoogleJavaFormatStep.defaultGroupArtifact(); String version = "1.11.0"; String style = ""; - boolean reflowLongStrings = false; + boolean reflowLongStrings; @Override protected void setupTest(API api) { diff --git a/testlib/src/test/java/com/diffplug/spotless/java/PalantirJavaFormatStepTest.java b/testlib/src/test/java/com/diffplug/spotless/java/PalantirJavaFormatStepTest.java index 642341cbc0..a0111ff347 100644 --- a/testlib/src/test/java/com/diffplug/spotless/java/PalantirJavaFormatStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/java/PalantirJavaFormatStepTest.java @@ -72,7 +72,7 @@ void equality() { new SerializableEqualityTester() { String version = "1.1.0"; String style = ""; - boolean formatJavadoc = false; + boolean formatJavadoc; @Override protected void setupTest(API api) { diff --git a/testlib/src/test/java/com/diffplug/spotless/json/JsonFormatterStepCommonTests.java b/testlib/src/test/java/com/diffplug/spotless/json/JsonFormatterStepCommonTests.java index 5f72ddb582..dc85e9c0d7 100644 --- a/testlib/src/test/java/com/diffplug/spotless/json/JsonFormatterStepCommonTests.java +++ b/testlib/src/test/java/com/diffplug/spotless/json/JsonFormatterStepCommonTests.java @@ -75,7 +75,7 @@ void canSetIndentationLevelTo0() throws Exception { @Test void equality() { new SerializableEqualityTester() { - int spaces = 0; + int spaces; @Override protected void setupTest(API api) { diff --git a/testlib/src/test/java/com/diffplug/spotless/json/JsonSimpleStepTest.java b/testlib/src/test/java/com/diffplug/spotless/json/JsonSimpleStepTest.java index c35760089a..444c94b37d 100644 --- a/testlib/src/test/java/com/diffplug/spotless/json/JsonSimpleStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/json/JsonSimpleStepTest.java @@ -105,7 +105,7 @@ void canSetIndentationLevelTo0() { @Test void equality() { new SerializableEqualityTester() { - int spaces = 0; + int spaces; @Override protected void setupTest(API api) { diff --git a/testlib/src/test/java/com/diffplug/spotless/npm/JsonWriterTest.java b/testlib/src/test/java/com/diffplug/spotless/npm/JsonWriterTest.java index cb1719c0f3..c2162547fd 100644 --- a/testlib/src/test/java/com/diffplug/spotless/npm/JsonWriterTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/npm/JsonWriterTest.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,7 +28,7 @@ class JsonWriterTest extends ResourceHarness { - private JsonWriter jsonWriter = new JsonWriter(); + private final JsonWriter jsonWriter = new JsonWriter(); @Test void itWritesAValidEmptyObject() { diff --git a/testlib/src/test/java/com/diffplug/spotless/npm/NpmFormatterStepCommonTests.java b/testlib/src/test/java/com/diffplug/spotless/npm/NpmFormatterStepCommonTests.java index 2672785453..4d59f043c7 100644 --- a/testlib/src/test/java/com/diffplug/spotless/npm/NpmFormatterStepCommonTests.java +++ b/testlib/src/test/java/com/diffplug/spotless/npm/NpmFormatterStepCommonTests.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. @@ -39,7 +39,7 @@ private File npmrc() { return new NpmrcResolver().tryFind().orElse(null); } - private File buildDir = null; + private File buildDir; protected File buildDir() { if (this.buildDir == null) { @@ -48,7 +48,7 @@ protected File buildDir() { return this.buildDir; } - private File projectDir = null; + private File projectDir; protected File projectDir() { if (this.projectDir == null) { diff --git a/testlib/src/test/java/com/diffplug/spotless/scala/ScalaFmtStepTest.java b/testlib/src/test/java/com/diffplug/spotless/scala/ScalaFmtStepTest.java index 1c534f5aef..e8485c680d 100644 --- a/testlib/src/test/java/com/diffplug/spotless/scala/ScalaFmtStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/scala/ScalaFmtStepTest.java @@ -57,16 +57,14 @@ void behaviorNoConfigFile() { @Test void behaviorConfigFileVersionDoesnotMatchLibrary() { FormatterStep step = ScalaFmtStep.create("3.0.0", TestProvisioner.mavenCentral(), createTestFile("scala/scalafmt/scalafmt.conf")); - Assertions.assertThatThrownBy(() -> { - step.format("", new File("")); - }).cause().message().contains("Spotless is using 3.0.0 but the config file declares 3.8.1. Both must match. Update the version declared in the plugin's settings and/or the config file."); + Assertions.assertThatThrownBy(() -> step.format("", new File(""))).cause().message().contains("Spotless is using 3.0.0 but the config file declares 3.8.1. Both must match. Update the version declared in the plugin's settings and/or the config file."); } @Test void equality() { new SerializableEqualityTester() { String version = "3.6.1"; - File configFile = null; + File configFile; @Override protected void setupTest(API api) { @@ -94,8 +92,6 @@ protected FormatterStep create() { void invalidConfiguration() { File invalidConfFile = createTestFile("scala/scalafmt/scalafmt.invalid.conf"); Provisioner provisioner = TestProvisioner.mavenCentral(); - Assertions.assertThatThrownBy(() -> { - ScalaFmtStep.create("3.0.0", provisioner, invalidConfFile).format("", new File("")); - }).cause().message().contains("found option 'invalidScalaFmtConfigField' which wasn't expected"); + Assertions.assertThatThrownBy(() -> ScalaFmtStep.create("3.0.0", provisioner, invalidConfFile).format("", new File(""))).cause().message().contains("found option 'invalidScalaFmtConfigField' which wasn't expected"); } }