Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -143,7 +145,7 @@ public String toString() {
}
for (Throwable error : errors) {
error.printStackTrace();
string.append(System.lineSeparator());
string.append(lineSeparator());
string.append(error.getMessage());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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;
};
}
}

Expand Down
4 changes: 3 additions & 1 deletion lib/src/main/java/com/diffplug/spotless/Jvm.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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")
Expand Down
138 changes: 70 additions & 68 deletions lib/src/main/java/com/diffplug/spotless/LineEnding.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -30,19 +32,20 @@
* 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();
}
},
/** 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();
}
Expand All @@ -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<Iterable<File>> toFormat) {
Expand All @@ -80,21 +82,21 @@ public Policy createPolicy(File projectDir, Supplier<Iterable<File>> 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;

Expand All @@ -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());

Expand All @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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';
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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(' ');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}
Expand Down
4 changes: 3 additions & 1 deletion lib/src/main/java/com/diffplug/spotless/pom/SortPomCfg.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
*/
package com.diffplug.spotless.pom;

import static java.lang.System.lineSeparator;

import java.io.Serial;
import java.io.Serializable;

Expand All @@ -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;

Expand Down
Loading
Loading