From 22911af29c2f97d633657382c16bf2477ae9a106 Mon Sep 17 00:00:00 2001 From: Vincent Potucek Date: Mon, 3 Nov 2025 12:21:58 +0100 Subject: [PATCH] [prone] Apply `UnnecessaryDefaultInEnumSwitch` --- .../jdt/DefaultJavaElementComparator.java | 33 +-- .../extra/GitAttributesLineEndings.java | 43 ++-- .../glue/ktfmt/KtfmtFormatterFunc.java | 1 - .../com/diffplug/spotless/LineEnding.java | 194 ++++++++++-------- .../com/diffplug/spotless/PaddedCell.java | 27 +-- .../biome/BiomeExecutableDownloader.java | 41 ++-- .../diffplug/spotless/biome/BiomeStep.java | 45 ++-- .../diffplug/spotless/generic/FenceStep.java | 17 +- .../diffplug/spotless/generic/IndentStep.java | 12 +- .../spotless/generic/LicenseHeaderStep.java | 36 ++-- .../java/RemoveUnusedImportsStep.java | 14 +- .../diffplug/spotless/kotlin/KtfmtStep.java | 16 +- .../sql/dbeaver/SQLTokenizedFormatter.java | 2 +- .../spotless/sql/dbeaver/SQLTokensParser.java | 58 +++--- .../gradle/spotless/GradleProvisioner.java | 14 +- .../spotless/GradleIntegrationHarness.java | 37 +--- .../spotless/maven/AbstractSpotlessMojo.java | 14 +- .../com/diffplug/spotless/PaddedCellTest.java | 16 +- 18 files changed, 275 insertions(+), 345 deletions(-) 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 6c1a576d58..f1c82f5d12 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 @@ -15,6 +15,8 @@ */ package com.diffplug.spotless.extra.glue.jdt; +import static org.eclipse.jdt.core.util.CompilationUnitSorter.RELATIVE_ORDER; + import java.util.Comparator; import java.util.List; import java.util.StringTokenizer; @@ -347,33 +349,18 @@ public int compare(BodyDeclaration bodyDeclaration1, BodyDeclaration bodyDeclara } private static int sortPreservedCategory(int category) { - switch (category) { - case STATIC_FIELDS_INDEX: - case STATIC_INIT_INDEX: - return STATIC_FIELDS_INDEX; - case FIELDS_INDEX: - case INIT_INDEX: - return FIELDS_INDEX; - default: - return category; - } + return switch (category) { + case STATIC_FIELDS_INDEX, STATIC_INIT_INDEX -> STATIC_FIELDS_INDEX; + case FIELDS_INDEX, INIT_INDEX -> FIELDS_INDEX; + default -> category; + }; } - private boolean isSortPreserved(BodyDeclaration bodyDeclaration) { - switch (bodyDeclaration.getNodeType()) { - case ASTNode.FIELD_DECLARATION: - case ASTNode.ENUM_CONSTANT_DECLARATION: - case ASTNode.INITIALIZER: - return true; - default: - return false; - } - } + private boolean isSortPreserved(BodyDeclaration bodyDeclaration) {return switch(bodyDeclaration.getNodeType()){case ASTNode.FIELD_DECLARATION,ASTNode.ENUM_CONSTANT_DECLARATION,ASTNode.INITIALIZER->true;default->false;};} private int preserveRelativeOrder(BodyDeclaration bodyDeclaration1, BodyDeclaration bodyDeclaration2) { - int value1 = (Integer) bodyDeclaration1.getProperty(CompilationUnitSorter.RELATIVE_ORDER); - int value2 = (Integer) bodyDeclaration2.getProperty(CompilationUnitSorter.RELATIVE_ORDER); - return value1 - value2; + return (Integer) bodyDeclaration1.getProperty(RELATIVE_ORDER) - + (Integer) bodyDeclaration2.getProperty(RELATIVE_ORDER); } private int compareNames(BodyDeclaration bodyDeclaration1, BodyDeclaration bodyDeclaration2, String name1, String name2) { diff --git a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java index af027ad42d..ef1f941b48 100644 --- a/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java +++ b/lib-extra/src/main/java/com/diffplug/spotless/extra/GitAttributesLineEndings.java @@ -15,6 +15,10 @@ */ package com.diffplug.spotless.extra; +import static com.diffplug.spotless.LineEnding.PLATFORM_NATIVE; +import static com.diffplug.spotless.LineEnding.UNIX; +import static com.diffplug.spotless.LineEnding.WINDOWS; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -91,10 +95,9 @@ public LazyAllTheSame(File projectDir, Supplier> toFormat) { protected String calculateState() throws Exception { var files = toFormat.get().iterator(); if (files.hasNext()) { - Runtime runtime = new RuntimeInit(projectDir).atRuntime(); - return runtime.getEndingFor(files.next()); + return new RuntimeInit(projectDir).atRuntime().getEndingFor(files.next()); } else { - return LineEnding.UNIX.str(); + return UNIX.str(); } } @@ -300,15 +303,14 @@ public String getEndingFor(File file) { } private static String convertEolToLineEnding(String eol, File file) { - switch (eol.toLowerCase(Locale.ROOT)) { - case "lf": - return LineEnding.UNIX.str(); - case "crlf": - return LineEnding.WINDOWS.str(); - default: - LOGGER.warn(".gitattributes file has unspecified eol value: {} for {}, defaulting to platform native", eol, file); - return LineEnding.PLATFORM_NATIVE.str(); - } + return switch (eol.toLowerCase(Locale.ROOT)) { + case "lf" -> UNIX.str(); + case "crlf" -> WINDOWS.str(); + default -> { + LOGGER.warn(".gitattributes file has unspecified eol value: {} for {}, defaulting to platform native", eol, file); + yield PLATFORM_NATIVE.str(); + } + }; } private LineEnding findDefaultLineEnding(Config config) { @@ -318,12 +320,12 @@ private LineEnding findDefaultLineEnding(Config config) { // autocrlf=true converts CRLF->LF during commit // and converts LF->CRLF during checkout // so CRLF is the default line ending - return LineEnding.WINDOWS; + return WINDOWS; } else if (autoCRLF == AutoCRLF.INPUT) { // autocrlf=input converts CRLF->LF during commit // and does no conversion during checkout // mostly used on Unix, so LF is the default encoding - return LineEnding.UNIX; + return UNIX; } else if (autoCRLF == AutoCRLF.FALSE) { // handle core.eol EOL eol = config.getEnum(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_EOL, EOL.NATIVE); @@ -335,14 +337,11 @@ private LineEnding findDefaultLineEnding(Config config) { /** Creates a LineEnding from an EOL. */ private static LineEnding fromEol(EOL eol) { - // @formatter:off - switch (eol) { - case CRLF: return LineEnding.WINDOWS; - case LF: return LineEnding.UNIX; - case NATIVE: return LineEnding.PLATFORM_NATIVE; - default: throw new IllegalArgumentException("Unknown eol " + eol); - } - // @formatter:on + return switch (eol) { + case CRLF -> WINDOWS; + case LF -> UNIX; + case NATIVE -> PLATFORM_NATIVE; + }; } } diff --git a/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java b/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java index 4b8308e47c..614eaafbe8 100644 --- a/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java +++ b/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java @@ -58,7 +58,6 @@ private FormattingOptions createFormattingOptions() throws Exception { case META -> Formatter.META_FORMAT; case GOOGLE -> Formatter.GOOGLE_FORMAT; case KOTLIN_LANG -> Formatter.KOTLINLANG_FORMAT; - default -> throw new IllegalStateException("Unknown formatting option " + style); }; if (ktfmtFormattingOptions != null) { diff --git a/lib/src/main/java/com/diffplug/spotless/LineEnding.java b/lib/src/main/java/com/diffplug/spotless/LineEnding.java index 7d7d46902a..a6235cf550 100644 --- a/lib/src/main/java/com/diffplug/spotless/LineEnding.java +++ b/lib/src/main/java/com/diffplug/spotless/LineEnding.java @@ -30,36 +30,53 @@ * Represents the line endings which should be written by the tool. */ public enum LineEnding { - // @formatter:off - /** Uses the same line endings as Git, using {@code .gitattributes} and the {@code core.eol} property. */ + /** + * Uses the same line endings as Git, using {@code .gitattributes} and the {@code core.eol} property. + */ GIT_ATTRIBUTES { /** .gitattributes is path-specific, so you must use {@link LineEnding#createPolicy(File, Supplier)}. */ - @Override @Deprecated + @Override + @Deprecated public Policy createPolicy() { return super.createPolicy(); } }, - /** Uses the same line endings as Git, and assumes that every single file being formatted will have the same line ending. */ + /** + * Uses the same line endings as Git, and assumes that every single file being formatted will have the same line + * ending. + */ GIT_ATTRIBUTES_FAST_ALLSAME { /** .gitattributes is path-specific, so you must use {@link LineEnding#createPolicy(File, Supplier)}. */ - @Override @Deprecated + @Override + @Deprecated public Policy createPolicy() { return super.createPolicy(); } }, - /** {@code \n} on unix systems, {@code \r\n} on windows systems. */ + /** + * {@code \n} on unix systems, {@code \r\n} on windows systems. + */ PLATFORM_NATIVE, - /** {@code \r\n} */ + /** + * {@code \r\n} + */ WINDOWS, - /** {@code \n} */ - UNIX, - /** {@code \r} */ - MAC_CLASSIC, - /** preserve the line ending of the first line (no matter which format) */ - PRESERVE; - // @formatter:on - - /** Returns a {@link Policy} appropriate for files which are contained within the given rootFolder. */ + /** + * {@code \n} + */ + UNIX, + /** + * {@code \r} + */ + MAC_CLASSIC, + /** + * preserve the line ending of the first line (no matter which format) + */ + PRESERVE; + + /** + * Returns a {@link Policy} appropriate for files which are contained within the given rootFolder. + */ public Policy createPolicy(File projectDir, Supplier> toFormat) { Objects.requireNonNull(projectDir, "projectDir"); Objects.requireNonNull(toFormat, "toFormat"); @@ -76,25 +93,29 @@ public Policy createPolicy(File projectDir, Supplier> toFormat) { Method method = clazz.getMethod(gitAttributesMethod, File.class, Supplier.class); return ThrowingEx.get(() -> (Policy) method.invoke(null, projectDir, toFormat)); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) { - throw new IllegalStateException("LineEnding.GIT_ATTRIBUTES requires the spotless-lib-extra library, but it is not on the classpath", e); + throw new IllegalStateException("LineEnding.GIT_ATTRIBUTES requires the spotless-lib-extra library, but it" + + " is not on the classpath", e); } } - // @formatter:off - /** Should use {@link #createPolicy(File, Supplier)} instead, but this will work iff its a path-independent LineEnding policy. */ + /** + * Should use {@link #createPolicy(File, Supplier)} instead, but this will work iff its a path-independent + * LineEnding policy. + */ public Policy createPolicy() { - switch (this) { - case PLATFORM_NATIVE: return _PLATFORM_NATIVE_POLICY; - case WINDOWS: return WINDOWS_POLICY; - case UNIX: return UNIX_POLICY; - case MAC_CLASSIC: return MAC_CLASSIC_POLICY; - case PRESERVE: return PRESERVE_POLICY; - default: throw new UnsupportedOperationException(this + " is a path-specific line ending."); - } + return switch (this) { + case PLATFORM_NATIVE -> _PLATFORM_NATIVE_POLICY; + case WINDOWS -> WINDOWS_POLICY; + case UNIX -> UNIX_POLICY; + case MAC_CLASSIC -> MAC_CLASSIC_POLICY; + case PRESERVE -> PRESERVE_POLICY; + default -> throw new UnsupportedOperationException(this + " is a path-specific line ending."); + }; } static class ConstantLineEndingPolicy extends NoLambda.EqualityBasedOnSerialization implements Policy { - @Serial private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; final String lineEnding; @@ -109,82 +130,89 @@ public String getEndingFor(File file) { } static class PreserveLineEndingPolicy extends NoLambda.EqualityBasedOnSerialization implements Policy { - @Serial private static final long serialVersionUID = 2L; - - @Override - public String getEndingFor(File file) { - // assume US-ASCII encoding (only line ending characters need to be decoded anyways) - try (Reader reader = new FileReader(file, StandardCharsets.US_ASCII)) { - return getEndingFor(reader); - } catch (IOException e) { - throw new IllegalArgumentException("Could not determine line ending of file: " + file, e); - } - } - - static String getEndingFor(Reader reader) throws IOException { - char previousCharacter = 0; - char currentCharacter = 0; - int readResult; - while ((readResult = reader.read()) != -1) { - currentCharacter = (char) readResult; - if (currentCharacter == '\n') { - if (previousCharacter == '\r') { - return WINDOWS.str(); - } else { - return UNIX.str(); - } - } else { - if (previousCharacter == '\r') { - return MAC_CLASSIC.str(); - } - } - previousCharacter = currentCharacter; - } - if (previousCharacter == '\r') { - return MAC_CLASSIC.str(); - } - // assume UNIX line endings if no line ending was found - return UNIX.str(); - } + @Serial + private static final long serialVersionUID = 2L; + + @Override + public String getEndingFor(File file) { + // assume US-ASCII encoding (only line ending characters need to be decoded anyways) + try (Reader reader = new FileReader(file, StandardCharsets.US_ASCII)) { + return getEndingFor(reader); + } catch (IOException e) { + throw new IllegalArgumentException("Could not determine line ending of file: " + file, e); + } + } + + static String getEndingFor(Reader reader) throws IOException { + char previousCharacter = 0; + char currentCharacter; + int readResult; + while ((readResult = reader.read()) != -1) { + currentCharacter = (char) readResult; + if (currentCharacter == '\n') { + if (previousCharacter == '\r') { + return WINDOWS.str(); + } else { + return UNIX.str(); + } + } else { + if (previousCharacter == '\r') { + return MAC_CLASSIC.str(); + } + } + previousCharacter = currentCharacter; + } + if (previousCharacter == '\r') { + return MAC_CLASSIC.str(); + } + // assume UNIX line endings if no line ending was found + return UNIX.str(); + } } private static final Policy WINDOWS_POLICY = new ConstantLineEndingPolicy(WINDOWS.str()); private static final Policy UNIX_POLICY = new ConstantLineEndingPolicy(UNIX.str()); - private static final Policy MAC_CLASSIC_POLICY = new ConstantLineEndingPolicy(MAC_CLASSIC.str()); - private static final Policy PRESERVE_POLICY = new PreserveLineEndingPolicy(); + private static final Policy MAC_CLASSIC_POLICY = new ConstantLineEndingPolicy(MAC_CLASSIC.str()); + private static final Policy PRESERVE_POLICY = new PreserveLineEndingPolicy(); private static final String _PLATFORM_NATIVE = System.getProperty("line.separator"); private static final Policy _PLATFORM_NATIVE_POLICY = new ConstantLineEndingPolicy(_PLATFORM_NATIVE); private static final boolean NATIVE_IS_WIN = _PLATFORM_NATIVE.equals(WINDOWS.str()); /** + * @see FileSignature#machineIsWin() * @deprecated Using the system-native line endings to detect the windows operating system has turned out * to be unreliable. Use {@link FileSignature#machineIsWin()} instead. - * - * @see FileSignature#machineIsWin() */ @Deprecated public static boolean nativeIsWin() { return NATIVE_IS_WIN; } - /** Returns the standard line ending for this policy. */ + /** + * Returns the standard line ending for this policy. + */ public String str() { - switch (this) { - case PLATFORM_NATIVE: return _PLATFORM_NATIVE; - case WINDOWS: return "\r\n"; - case UNIX: return "\n"; - case MAC_CLASSIC: return "\r"; - default: throw new UnsupportedOperationException(this + " is a path-specific line ending."); - } + return switch (this) { + case PLATFORM_NATIVE -> _PLATFORM_NATIVE; + case WINDOWS -> "\r\n"; + case UNIX -> "\n"; + case MAC_CLASSIC -> "\r"; + default -> throw new UnsupportedOperationException(this + " is a path-specific line ending."); + }; } - // @formatter:on - /** A policy for line endings which can vary based on the specific file being requested. */ + /** + * A policy for line endings which can vary based on the specific file being requested. + */ public interface Policy extends Serializable, NoLambda { - /** Returns the line ending appropriate for the given file. */ + /** + * Returns the line ending appropriate for the given file. + */ String getEndingFor(File file); - /** Returns true iff this file has unix line endings. */ + /** + * Returns true iff this file has unix line endings. + */ public default boolean isUnix(File file) { Objects.requireNonNull(file); String ending = getEndingFor(file); @@ -192,7 +220,9 @@ public default boolean isUnix(File file) { } } - /** Returns a string with exclusively unix line endings. */ + /** + * Returns a string with exclusively unix line endings. + */ public static String toUnix(String input) { int lastCarriageReturn = input.lastIndexOf('\r'); if (lastCarriageReturn == -1) { diff --git a/lib/src/main/java/com/diffplug/spotless/PaddedCell.java b/lib/src/main/java/com/diffplug/spotless/PaddedCell.java index f6973a6daa..4626fc0a9e 100644 --- a/lib/src/main/java/com/diffplug/spotless/PaddedCell.java +++ b/lib/src/main/java/com/diffplug/spotless/PaddedCell.java @@ -150,25 +150,20 @@ public boolean isResolvable() { /** Returns the "canonical" form for this particular result (only possible if isResolvable). */ public String canonical() { - // @formatter:off - switch (type) { - case CONVERGE: return steps.get(steps.size() - 1); - case CYCLE: return Collections.min(steps, Comparator.comparingInt(String::length).thenComparing(Function.identity())); - case DIVERGE: throw new IllegalArgumentException("No canonical form for a diverging result"); - default: throw new IllegalArgumentException("Unknown type: " + type); - } - // @formatter:on + return switch (type) { + case CONVERGE -> steps.get(steps.size() - 1); + case CYCLE -> + Collections.min(steps, Comparator.comparingInt(String::length).thenComparing(Function.identity())); + case DIVERGE -> throw new IllegalArgumentException("No canonical form for a diverging result"); + }; } /** Returns a string which describes this result. */ public String userMessage() { - // @formatter:off - switch (type) { - case CONVERGE: return "converges after " + steps.size() + " steps"; - case CYCLE: return "cycles between " + steps.size() + " steps"; - case DIVERGE: return "diverges after " + steps.size() + " steps"; - default: throw new IllegalArgumentException("Unknown type: " + type); - } - // @formatter:on + return switch (type) { + case CONVERGE -> "converges after " + steps.size() + " steps"; + case CYCLE -> "cycles between " + steps.size() + " steps"; + case DIVERGE -> "diverges after " + steps.size() + " steps"; + }; } } diff --git a/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java b/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java index 0b2b1a6575..afe02ef8d8 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeExecutableDownloader.java @@ -241,14 +241,10 @@ private String computeChecksum(Path file, String algorithm) throws IOException { * @throws IOException When the given OS is not supported by Biome. */ private String getArchitectureCodeName(Architecture architecture) throws IOException { - switch (architecture) { - case ARM64: - return "arm64"; - case X64: - return "x64"; - default: - throw new IOException("Unsupported architecture: " + architecture); - } + return switch (architecture) { + case ARM64 -> "arm64"; + case X64 -> "x64"; + }; } /** @@ -290,16 +286,10 @@ private String getDownloadUrl(String version, Platform platform) throws IOExcept * @throws IOException When the given OS is not supported by Biome. */ private String getDownloadUrlExtension(OS os) throws IOException { - switch (os) { - case LINUX: - return ""; - case MAC_OS: - return ""; - case WINDOWS: - return ".exe"; - default: - throw new IOException("Unsupported OS: " + os); - } + return switch (os) { + case LINUX, MAC_OS -> ""; + case WINDOWS -> ".exe"; + }; } /** @@ -326,16 +316,11 @@ private Path getExecutablePath(String version, Platform platform) { * @throws IOException When the given OS is not supported by Biome. */ private String getOsCodeName(OS os) throws IOException { - switch (os) { - case LINUX: - return "linux"; - case MAC_OS: - return "darwin"; - case WINDOWS: - return "win32"; - default: - throw new IOException("Unsupported OS: " + os); - } + return switch (os) { + case LINUX -> "linux"; + case MAC_OS -> "darwin"; + case WINDOWS -> "win32"; + }; } /** 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 848481e07e..107d84a6fd 100644 --- a/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java +++ b/lib/src/main/java/com/diffplug/spotless/biome/BiomeStep.java @@ -456,32 +456,22 @@ private String resolveFileName(File file) { } var dot = name.lastIndexOf("."); var ext = dot >= 0 ? name.substring(dot + 1) : name; - switch (language) { - case "js?": - return "jsx".equals(ext) || "js".equals(ext) || "mjs".equals(ext) || "cjs".equals(ext) ? name - : "file.js"; - case "ts?": - return "tsx".equals(ext) || "ts".equals(ext) || "mts".equals(ext) || "cts".equals(ext) ? name - : "file.js"; - case "js": - return "js".equals(ext) || "mjs".equals(ext) || "cjs".equals(ext) ? name : "file.js"; - case "jsx": - return "jsx".equals(ext) ? name : "file.jsx"; - case "ts": - return "ts".equals(ext) || "mts".equals(ext) || "cts".equals(ext) ? name : "file.ts"; - case "tsx": - return "tsx".equals(ext) ? name : "file.tsx"; - case "json": - return "json".equals(ext) ? name : "file.json"; - case "jsonc": - return "jsonc".equals(ext) ? name : "file.jsonc"; - case "css": - return "css".equals(ext) ? name : "file.css"; - // so that we can support new languages such as css or yaml when Biome adds - // support for them without having to change the code - default: - return "file." + language; - } + return switch (language) { + case "js?" -> "jsx".equals(ext) || "js".equals(ext) || "mjs".equals(ext) || "cjs".equals(ext) ? name + : "file.js"; + case "ts?" -> "tsx".equals(ext) || "ts".equals(ext) || "mts".equals(ext) || "cts".equals(ext) ? name + : "file.js"; + case "js" -> "js".equals(ext) || "mjs".equals(ext) || "cjs".equals(ext) ? name : "file.js"; + case "jsx" -> "jsx".equals(ext) ? name : "file.jsx"; + case "ts" -> "ts".equals(ext) || "mts".equals(ext) || "cts".equals(ext) ? name : "file.ts"; + case "tsx" -> "tsx".equals(ext) ? name : "file.tsx"; + case "json" -> "json".equals(ext) ? name : "file.json"; + case "jsonc" -> "jsonc".equals(ext) ? name : "file.jsonc"; + case "css" -> "css".equals(ext) ? name : "file.css"; + // so that we can support new languages such as css or yaml when Biome adds + // support for them without having to change the code + default -> "file." + language; + }; } /** @@ -491,8 +481,7 @@ private String resolveFileName(File file) { * @return A formatter function for formatting code. */ private FormatterFunc.Closeable toFunc() { - var runner = new ProcessRunner(); - return FormatterFunc.Closeable.of(runner, this::format); + return FormatterFunc.Closeable.of(new ProcessRunner(), this::format); } } } diff --git a/lib/src/main/java/com/diffplug/spotless/generic/FenceStep.java b/lib/src/main/java/com/diffplug/spotless/generic/FenceStep.java index 6d52435a56..7922ff80f4 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/FenceStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/FenceStep.java @@ -15,6 +15,9 @@ */ package com.diffplug.spotless.generic; +import static com.diffplug.spotless.generic.FenceStep.Kind.APPLY; +import static com.diffplug.spotless.generic.FenceStep.Kind.PRESERVE; + import java.io.File; import java.io.Serializable; import java.nio.charset.StandardCharsets; @@ -78,7 +81,7 @@ private void assertRegexSet() { /** Returns a step which will apply the given steps but preserve the content selected by the regex / openClose pair. */ public FormatterStep preserveWithin(List steps) { - return createStep(Kind.PRESERVE, steps); + return createStep(PRESERVE, steps); } /** @@ -86,7 +89,7 @@ public FormatterStep preserveWithin(List steps) { * Linting within the substeps is not supported. */ public FormatterStep applyWithin(List steps) { - return createStep(Kind.APPLY, steps); + return createStep(APPLY, steps); } private FormatterStep createStep(Kind kind, List steps) { @@ -96,7 +99,7 @@ private FormatterStep createStep(Kind kind, List steps) { RoundtripAndEqualityState::toFormatterFunc); } - private enum Kind { + enum Kind { APPLY, PRESERVE } @@ -210,24 +213,22 @@ public String applyWithFile(String unix, File file) throws Exception { } List groups = groupsZeroed(); Matcher matcher = regex.matcher(unix); - switch (kind) { - case APPLY: + if (kind == APPLY) { while (matcher.find()) { // apply the formatter to each group groups.add(formatter.compute(matcher.group(1), file)); } // and then assemble the result right away return assembleGroups(unix); - case PRESERVE: + } else if (kind == PRESERVE) { while (matcher.find()) { // store whatever is within the open/close tags groups.add(matcher.group(1)); } String formatted = formatter.compute(unix, file); return assembleGroups(formatted); - default: - throw new Error(); } + throw new Error(); } @Override 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 00077f8c90..3166964b7c 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java @@ -15,6 +15,9 @@ */ package com.diffplug.spotless.generic; +import static com.diffplug.spotless.generic.IndentStep.Type.SPACE; +import static com.diffplug.spotless.generic.IndentStep.Type.TAB; + import java.io.Serial; import java.io.Serializable; @@ -102,22 +105,17 @@ String format(String raw) { // add the leading space in a canonical way if (numSpaces > 0) { - switch (state.type) { - case SPACE: + if (state.type == SPACE) { for (int i = 0; i < numSpaces; i++) { builder.append(' '); } - break; - case TAB: + } else if (state.type == TAB) { for (int i = 0; i < numSpaces / state.numSpacesPerTab; i++) { builder.append('\t'); } if (mightBeMultiLineComment && (numSpaces % state.numSpacesPerTab == 1)) { builder.append(' '); } - break; - default: - throw new IllegalArgumentException("Unexpected enum " + state.type); } } 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 8f054645f7..159b470ff7 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/LicenseHeaderStep.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless.generic; +import static com.diffplug.spotless.FormatterStep.createLazy; + import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -132,27 +134,21 @@ public FormatterFunc apply(Runtime input) throws Exception { public FormatterStep build() { FormatterStep formatterStep; if (yearMode.get() == YearMode.SET_FROM_GIT) { - formatterStep = FormatterStep.createLazy(name, () -> { - boolean updateYear = false; // doesn't matter - return new Runtime(headerLazy.get(), delimiter, yearSeparator, updateYear, skipLinesMatching); - }, new SetLicenseHeaderYearsFromGitHistory()); + formatterStep = createLazy( + name, + () -> new Runtime(headerLazy.get(), delimiter, yearSeparator, false, skipLinesMatching), + new SetLicenseHeaderYearsFromGitHistory()); } else { - formatterStep = FormatterStep.createLazy(name, () -> { - // by default, we should update the year if the user is using ratchetFrom - boolean updateYear; - switch (yearMode.get()) { - case PRESERVE: - updateYear = false; - break; - case UPDATE_TO_TODAY: - updateYear = true; - break; - case SET_FROM_GIT: - default: - throw new IllegalStateException(yearMode.toString()); - } - return new Runtime(headerLazy.get(), delimiter, yearSeparator, updateYear, skipLinesMatching); - }, step -> FormatterFunc.needsFile(step::format)); + formatterStep = createLazy( + name, + () -> new Runtime(headerLazy.get(), delimiter, yearSeparator, + // by default, we should update the year if the user is using ratchetFrom + switch (yearMode.get()) { + case PRESERVE -> false; + case UPDATE_TO_TODAY -> true; + default -> throw new IllegalStateException(yearMode.toString()); + }, skipLinesMatching), + step -> FormatterFunc.needsFile(step::format)); } if (contentPattern == null) { return formatterStep; diff --git a/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java b/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java index 590432aedc..00a043068f 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java @@ -49,13 +49,11 @@ public static FormatterStep create(Provisioner provisioner) { public static FormatterStep create(String unusedImportRemover, Provisioner provisioner) { Objects.requireNonNull(provisioner, "provisioner"); - switch (unusedImportRemover) { - case GJF: - return GoogleJavaFormatStep.createRemoveUnusedImportsOnly(provisioner); - case CLEANTHAT: - return CleanthatJavaStep.createWithStepName(NAME, CleanthatJavaStep.defaultGroupArtifact(), CleanthatJavaStep.defaultVersion(), "99.9", List.of(CLEANTHAT_MUTATOR), List.of(), false, provisioner); - default: - throw new IllegalArgumentException("Invalid unusedImportRemover: " + unusedImportRemover); - } + return switch (unusedImportRemover) { + case GJF -> GoogleJavaFormatStep.createRemoveUnusedImportsOnly(provisioner); + case CLEANTHAT -> + CleanthatJavaStep.createWithStepName(NAME, CleanthatJavaStep.defaultGroupArtifact(), CleanthatJavaStep.defaultVersion(), "99.9", List.of(CLEANTHAT_MUTATOR), List.of(), false, provisioner); + default -> throw new IllegalArgumentException("Invalid unusedImportRemover: " + unusedImportRemover); + }; } } 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 be1ef132ec..6cefd4e0df 100644 --- a/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java +++ b/lib/src/main/java/com/diffplug/spotless/kotlin/KtfmtStep.java @@ -325,16 +325,12 @@ private void validateStyle() { * @return com.diffplug.spotless.glue.ktfmt.KtfmtStyle enum value name */ private String getKtfmtStyleOption(Style style) { - switch (style) { - case META: - return "META"; - case GOOGLE: - return "GOOGLE"; - case KOTLINLANG: - return "KOTLIN_LANG"; - default: - throw new IllegalStateException("Unsupported style: " + style); - } + return switch (style) { + case META -> "META"; + case GOOGLE -> "GOOGLE"; + case KOTLINLANG -> "KOTLIN_LANG"; + default -> throw new IllegalStateException("Unsupported style: " + style); + }; } } 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 52665bf716..30e570379d 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 @@ -125,7 +125,7 @@ private List format(final List argList) { // 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))) { + || ("START".equals(tokenString) && "WITH".equals(token2String))) { t0.setString(t0.getString() + " " + t2.getString()); argList.remove(index + 1); argList.remove(index + 1); diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/SQLTokensParser.java index 3216f9990e..287d100287 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 @@ -71,35 +71,35 @@ private static boolean isDigit(final char argChar) { } private static boolean isSymbol(final char argChar) { - switch (argChar) { - case '"': // double quote - case '?': // question mark - case '%': // percent - case '&': // ampersand - case '\'': // quote - case '(': // left paren - case ')': // right paren - case '|': // vertical bar - case '*': // asterisk - case '+': // plus sign - case ',': // comma - case '-': // minus sign - case '.': // period - case '/': // solidus - case ':': // colon - case ';': // semicolon - case '<': // less than operator - case '=': // equals operator - case '>': // greater than operator - case '!': // greater than operator - case '~': // greater than operator - case '`': // apos - case '[': // bracket open - case ']': // bracket close - return true; - default: - return false; - } + // @formatter:off + return switch (argChar) { + case '!' -> true; // exclamation mark + case '"' -> true; // double quote + case '%' -> true; // percent + case '&' -> true; // ampersand + case '(' -> true; // left paren + case ')' -> true; // right paren + case '*' -> true; // asterisk + case '+' -> true; // plus sign + case ',' -> true; // comma + case '-' -> true; // minus sign + case '.' -> true; // period + case '/' -> true; // solidus + case ':' -> true; // colon + case ';' -> true; // semicolon + case '<' -> true; // less than operator + case '=' -> true; // equals operator + case '>' -> true; // greater than operator + case '?' -> true; // question mark + case '[' -> true; // bracket open + case '\'' -> true;// quote + case ']' -> true; // bracket close + case '`' -> true; // backtick + case '|' -> true; // vertical bar + case '~' -> true; // tilde + default -> false; + }; + // @formatter:on } private FormatterToken nextToken() { 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 b8260e3b9c..e70340c8fe 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 @@ -45,15 +45,11 @@ enum Policy { INDEPENDENT, ROOT_PROJECT, ROOT_BUILDSCRIPT; public DedupingProvisioner dedupingProvisioner(Project project) { - switch (this) { - case ROOT_PROJECT: - return new DedupingProvisioner(forProject(project)); - case ROOT_BUILDSCRIPT: - return new DedupingProvisioner(forRootProjectBuildscript(project)); - case INDEPENDENT: - default: - throw Unhandled.enumException(this); - } + return switch (this) { + case ROOT_PROJECT -> new DedupingProvisioner(forProject(project)); + case ROOT_BUILDSCRIPT -> new DedupingProvisioner(forRootProjectBuildscript(project)); + case INDEPENDENT -> throw Unhandled.enumException(this); + }; } } 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 3402cbada3..b2b5700ccf 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 @@ -56,40 +56,9 @@ public enum GradleVersionSupport { final String version; GradleVersionSupport(String version) { - String minVersionForRunningJRE; - switch (Jvm.version()) { - case 25: - // TODO: https://docs.gradle.org/current/userguide/compatibility.html - case 24: - minVersionForRunningJRE = "8.14"; - break; - case 23: - minVersionForRunningJRE = "8.10"; - break; - case 22: - minVersionForRunningJRE = "8.8"; - break; - case 21: - minVersionForRunningJRE = "8.5"; - break; - case 20: - minVersionForRunningJRE = "8.3"; - break; - case 19: - minVersionForRunningJRE = "7.6"; - break; - case 18: - minVersionForRunningJRE = "7.5"; - break; - default: - minVersionForRunningJRE = null; - break; - } - if (minVersionForRunningJRE != null && GradleVersion.version(minVersionForRunningJRE).compareTo(GradleVersion.version(version)) > 0) { - this.version = minVersionForRunningJRE; - } else { - this.version = version; - } + String minVersionForRunningJRE=switch(Jvm.version()){ + // TODO: https://docs.gradle.org/current/userguide/compatibility.html + case 25,24->"8.14";case 23->"8.10";case 22->"8.8";case 21->"8.5";case 20->"8.3";case 19->"7.6";case 18->"7.5";default->null;};if(minVersionForRunningJRE!=null&&GradleVersion.version(minVersionForRunningJRE).compareTo(GradleVersion.version(version))>0){this.version=minVersionForRunningJRE;}else{this.version=version;} } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java index 3952a8de70..c86d2de588 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java @@ -288,16 +288,12 @@ private boolean shouldSkip() { return true; } - switch (goal) { - case GOAL_CHECK: - return checkSkip; - case GOAL_APPLY: - return applySkip; - default: - break; - } + return switch (goal) { + case GOAL_CHECK -> checkSkip; + case GOAL_APPLY -> applySkip; + default -> false; + }; - return false; } private List collectFiles(FormatterFactory formatterFactory, FormatterConfig config) { diff --git a/testlib/src/test/java/com/diffplug/spotless/PaddedCellTest.java b/testlib/src/test/java/com/diffplug/spotless/PaddedCellTest.java index 2820aadeef..53fae83845 100644 --- a/testlib/src/test/java/com/diffplug/spotless/PaddedCellTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/PaddedCellTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2024 DiffPlug + * Copyright 2016-2025 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,15 +84,11 @@ void pingPong() throws IOException { @Test void fourState() throws IOException { - misbehaved(input -> { - // @formatter:off - switch (input) { - case "A": return "B"; - case "B": return "C"; - case "C": return "D"; - default: return "A"; - } - // @formatter:on + misbehaved(input -> switch (input) { + case "A" -> "B"; + case "B" -> "C"; + case "C" -> "D"; + default -> "A"; }, "CCC", CYCLE, "A,B,C,D", "A"); }