From 18f0eb89167fdeef50974780700477ff55198f21 Mon Sep 17 00:00:00 2001 From: Vincent Potucek Date: Mon, 3 Nov 2025 11:12:31 +0100 Subject: [PATCH 1/2] Can be replaced with `String.repeat()` --- .../spotless/generic/EndWithNewlineStep.java | 7 ++----- .../com/diffplug/spotless/generic/IndentStep.java | 8 ++------ .../dbeaver/DBeaverSQLFormatterConfiguration.java | 15 ++++++--------- .../spotless/sql/dbeaver/FormatterToken.java | 12 +++++------- .../sql/dbeaver/SQLTokenizedFormatter.java | 4 +--- 5 files changed, 16 insertions(+), 30 deletions(-) diff --git a/lib/src/main/java/com/diffplug/spotless/generic/EndWithNewlineStep.java b/lib/src/main/java/com/diffplug/spotless/generic/EndWithNewlineStep.java index bd9a93a6e8..3234753226 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/EndWithNewlineStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/EndWithNewlineStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 DiffPlug + * Copyright 2016-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,10 +52,7 @@ private static String format(String rawUnix) { } else if (lastContentCharacter == rawUnix.length() - 2 && rawUnix.charAt(rawUnix.length() - 1) == '\n') { return rawUnix; } else { - StringBuilder builder = new StringBuilder(lastContentCharacter + 2); - builder.append(rawUnix, 0, lastContentCharacter + 1); - builder.append('\n'); - return builder.toString(); + return rawUnix.substring(0, lastContentCharacter + 1) + '\n'; } } } 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..4a829e7f43 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java @@ -104,14 +104,10 @@ String format(String raw) { if (numSpaces > 0) { switch (state.type) { case SPACE: - for (int i = 0; i < numSpaces; i++) { - builder.append(' '); - } + builder.append(" ".repeat(numSpaces)); break; case TAB: - for (int i = 0; i < numSpaces / state.numSpacesPerTab; i++) { - builder.append('\t'); - } + builder.append("\t".repeat(numSpaces / state.numSpacesPerTab)); if (mightBeMultiLineComment && (numSpaces % state.numSpacesPerTab == 1)) { builder.append(' '); } diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/DBeaverSQLFormatterConfiguration.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/DBeaverSQLFormatterConfiguration.java index 02e236d4a4..083b196a96 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/DBeaverSQLFormatterConfiguration.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/DBeaverSQLFormatterConfiguration.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless.sql.dbeaver; +import static java.lang.Integer.parseInt; + import java.util.Properties; import com.diffplug.spotless.annotations.Internal; @@ -59,18 +61,13 @@ public DBeaverSQLFormatterConfiguration(Properties properties) { this.keywordCase = KeywordCase.valueOf(properties.getProperty(SQL_FORMATTER_KEYWORD_CASE, "UPPER")); this.statementDelimiters = properties.getProperty(SQL_FORMATTER_STATEMENT_DELIMITER, SQLDialect.INSTANCE .getScriptDelimiter()); - String indentType = properties.getProperty(SQL_FORMATTER_INDENT_TYPE, "space"); - int indentSize = Integer.parseInt(properties.getProperty(SQL_FORMATTER_INDENT_SIZE, "4")); - indentString = getIndentString(indentType, indentSize); + indentString = getIndentString( + properties.getProperty(SQL_FORMATTER_INDENT_TYPE, "space"), + parseInt(properties.getProperty(SQL_FORMATTER_INDENT_SIZE, "4"))); } private String getIndentString(String indentType, int indentSize) { - char indentChar = "space".equals(indentType) ? ' ' : '\t'; - StringBuilder stringBuilder = new StringBuilder(); - for (int i = 0; i < indentSize; i++) { - stringBuilder.append(indentChar); - } - return stringBuilder.toString(); + return String.valueOf("space".equals(indentType) ? ' ' : '\t').repeat(indentSize); } String getStatementDelimiter() { diff --git a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/FormatterToken.java b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/FormatterToken.java index f608a1686f..4662744bf0 100644 --- a/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/FormatterToken.java +++ b/lib/src/main/java/com/diffplug/spotless/sql/dbeaver/FormatterToken.java @@ -65,12 +65,10 @@ public int getPos() { @Override public String toString() { - final StringBuilder buf = new StringBuilder(); - buf.append(getClass().getName()); - buf.append("type=").append(fType); - buf.append(",string=").append(fString); - buf.append(",pos=").append(fPos); - buf.append("]"); - return buf.toString(); + return getClass().getName() + + "type=" + fType + + ",string=" + fString + + ",pos=" + fPos + + "]"; } } 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..6e8054d62c 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 @@ -399,9 +399,7 @@ private int insertReturnAndIndent(final List argList, final int try { final String defaultLineSeparator = getDefaultLineSeparator(); StringBuilder s = new StringBuilder(defaultLineSeparator); - for (int index = 0; index < argIndent; index++) { - s.append(formatterCfg.getIndentString()); - } + s.append(formatterCfg.getIndentString().repeat(argIndent)); if (argIndex > 0) { final FormatterToken token = argList.get(argIndex); final FormatterToken prevToken = argList.get(argIndex - 1); From b0a1b929f5eab4110d1505ffc385fde084faa6ff Mon Sep 17 00:00:00 2001 From: Vincent Potucek Date: Mon, 3 Nov 2025 12:20:11 +0100 Subject: [PATCH 2/2] Can be replaced with `String.repeat()` --- .../groovy/GrEclipseFormatterStepImpl.java | 4 +- .../jdt/DefaultJavaElementComparator.java | 26 +--- .../extra/GitAttributesLineEndings.java | 30 ++-- .../main/java/com/diffplug/spotless/Jvm.java | 4 +- .../com/diffplug/spotless/LineEnding.java | 138 +++++++++--------- .../spotless/groovy/RemoveSemicolonsStep.java | 4 +- .../com/diffplug/spotless/pom/SortPomCfg.java | 4 +- .../diffplug/spotless/pom/SortPomCfgTest.java | 3 +- 8 files changed, 103 insertions(+), 110 deletions(-) diff --git a/lib-extra/src/groovy/java/com/diffplug/spotless/extra/glue/groovy/GrEclipseFormatterStepImpl.java b/lib-extra/src/groovy/java/com/diffplug/spotless/extra/glue/groovy/GrEclipseFormatterStepImpl.java index 682e9bddbb..3399611fc6 100644 --- a/lib-extra/src/groovy/java/com/diffplug/spotless/extra/glue/groovy/GrEclipseFormatterStepImpl.java +++ b/lib-extra/src/groovy/java/com/diffplug/spotless/extra/glue/groovy/GrEclipseFormatterStepImpl.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless.extra.glue.groovy; +import static java.lang.System.lineSeparator; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -143,7 +145,7 @@ public String toString() { } for (Throwable error : errors) { error.printStackTrace(); - string.append(System.lineSeparator()); + string.append(lineSeparator()); string.append(error.getMessage()); } 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..d659e8e2f8 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 @@ -347,28 +347,14 @@ 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); 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..ce0fa6b2f2 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 @@ -300,15 +300,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" -> LineEnding.UNIX.str(); + case "crlf" -> LineEnding.WINDOWS.str(); + default -> { + LOGGER.warn(".gitattributes file has unspecified eol value: {} for {}, defaulting to platform native", eol, file); + yield LineEnding.PLATFORM_NATIVE.str(); + } + }; } private LineEnding findDefaultLineEnding(Config config) { @@ -335,14 +334,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 -> LineEnding.WINDOWS; + case LF -> LineEnding.UNIX; + case NATIVE -> LineEnding.PLATFORM_NATIVE; + }; } } diff --git a/lib/src/main/java/com/diffplug/spotless/Jvm.java b/lib/src/main/java/com/diffplug/spotless/Jvm.java index 7d8812546b..7ec531973f 100644 --- a/lib/src/main/java/com/diffplug/spotless/Jvm.java +++ b/lib/src/main/java/com/diffplug/spotless/Jvm.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless; +import static java.lang.System.lineSeparator; + import java.io.File; import java.util.Arrays; import java.util.Comparator; @@ -253,7 +255,7 @@ private String buildUpgradeFormatterMessage(V fmtVersion) { public String toString() { return "%s alternatives:%n".formatted(fmtName) + jvm2fmtMaxVersion.entrySet().stream().map( - e -> "- Version %s requires JVM %d+".formatted(e.getValue(), e.getKey())).collect(Collectors.joining(System.lineSeparator())); + e -> "- Version %s requires JVM %d+".formatted(e.getValue(), e.getKey())).collect(Collectors.joining(lineSeparator())); } @SuppressFBWarnings("SE_COMPARATOR_SHOULD_BE_SERIALIZABLE") diff --git a/lib/src/main/java/com/diffplug/spotless/LineEnding.java b/lib/src/main/java/com/diffplug/spotless/LineEnding.java index 7d7d46902a..653beec423 100644 --- a/lib/src/main/java/com/diffplug/spotless/LineEnding.java +++ b/lib/src/main/java/com/diffplug/spotless/LineEnding.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless; +import static java.lang.System.lineSeparator; + import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -30,11 +32,11 @@ * 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. */ 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(); } @@ -42,7 +44,8 @@ public Policy createPolicy() { /** Uses the same line endings as Git, and assumes that every single file being formatted will have the same line ending. */ GIT_ATTRIBUTES_FAST_ALLSAME { /** .gitattributes is path-specific, so you must use {@link LineEnding#createPolicy(File, Supplier)}. */ - @Override @Deprecated + @Override + @Deprecated public Policy createPolicy() { return super.createPolicy(); } @@ -51,13 +54,12 @@ public Policy createPolicy() { PLATFORM_NATIVE, /** {@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 + /** {@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) { @@ -80,21 +82,21 @@ public Policy createPolicy(File projectDir, Supplier> toFormat) { } } - // @formatter:off /** 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,50 +111,51 @@ 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 String _PLATFORM_NATIVE = System.getProperty("line.separator"); + 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 = lineSeparator(); private static final Policy _PLATFORM_NATIVE_POLICY = new ConstantLineEndingPolicy(_PLATFORM_NATIVE); private static final boolean NATIVE_IS_WIN = _PLATFORM_NATIVE.equals(WINDOWS.str()); @@ -169,15 +172,14 @@ public static boolean nativeIsWin() { /** 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. */ public interface Policy extends Serializable, NoLambda { diff --git a/lib/src/main/java/com/diffplug/spotless/groovy/RemoveSemicolonsStep.java b/lib/src/main/java/com/diffplug/spotless/groovy/RemoveSemicolonsStep.java index c701be63ee..0caba029d7 100644 --- a/lib/src/main/java/com/diffplug/spotless/groovy/RemoveSemicolonsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/groovy/RemoveSemicolonsStep.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless.groovy; +import static java.lang.System.lineSeparator; + import java.io.BufferedReader; import java.io.Serial; import java.io.Serializable; @@ -54,7 +56,7 @@ FormatterFunc toFormatter() { String line; while ((line = reader.readLine()) != null) { result.append(removeSemicolon(line)); - result.append(System.lineSeparator()); + result.append(lineSeparator()); } return result.toString(); } 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 9825cfa4d8..a31ac84969 100644 --- a/lib/src/main/java/com/diffplug/spotless/pom/SortPomCfg.java +++ b/lib/src/main/java/com/diffplug/spotless/pom/SortPomCfg.java @@ -15,6 +15,8 @@ */ package com.diffplug.spotless.pom; +import static java.lang.System.lineSeparator; + import java.io.Serial; import java.io.Serializable; @@ -27,7 +29,7 @@ public class SortPomCfg implements Serializable { public String encoding = "UTF-8"; - public String lineSeparator = System.getProperty("line.separator"); + public String lineSeparator = lineSeparator(); public boolean expandEmptyElements; diff --git a/lib/src/test/java/com/diffplug/spotless/pom/SortPomCfgTest.java b/lib/src/test/java/com/diffplug/spotless/pom/SortPomCfgTest.java index b0a336f189..4ce97d0355 100644 --- a/lib/src/test/java/com/diffplug/spotless/pom/SortPomCfgTest.java +++ b/lib/src/test/java/com/diffplug/spotless/pom/SortPomCfgTest.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.pom; +import static java.lang.System.lineSeparator; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; @@ -28,7 +29,7 @@ void testDefaultValues() { // Test default values using AssertJ assertThat(cfg.version).isEqualTo("4.0.0"); assertThat(cfg.encoding).isEqualTo("UTF-8"); - assertThat(cfg.lineSeparator).isEqualTo(System.getProperty("line.separator")); + assertThat(cfg.lineSeparator).isEqualTo(lineSeparator()); assertThat(cfg.expandEmptyElements).isFalse(); assertThat(cfg.spaceBeforeCloseEmptyElement).isFalse(); assertThat(cfg.keepBlankLines).isTrue();