Skip to content

Commit 585d0a5

Browse files
committed
Speedup LineEnding.toUnix, and add a test.
1 parent 1cd8553 commit 585d0a5

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

lib/src/main/java/com/diffplug/spotless/LineEnding.java

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -142,14 +142,17 @@ public default boolean isUnix(File file) {
142142

143143
/** Returns a string with exclusively unix line endings. */
144144
public static String toUnix(String input) {
145-
if (input.lastIndexOf(WINDOWS.str()) > -1) {
146-
return input.replace("\r", "");
147-
} else if (input.lastIndexOf(MAC_CLASSIC.str()) > -1) {
148-
// replace mac classic '\r' with unix line endings '\n'
149-
return input.replace(MAC_CLASSIC.str(), UNIX.str());
150-
} else {
151-
// fastest way to detect if a string is already unix-only
145+
int lastCarriageReturn = input.lastIndexOf('\r');
146+
if (lastCarriageReturn == -1) {
152147
return input;
148+
} else {
149+
if (input.lastIndexOf("\r\n") == -1) {
150+
// it is MAC_CLASSIC \r
151+
return input.replace('\r', '\n');
152+
} else {
153+
// it is WINDOWS \r\n
154+
return input.replace("\r", "");
155+
}
153156
}
154157
}
155158
}

testlib/src/test/java/com/diffplug/spotless/FormatterTest.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2016-2021 DiffPlug
2+
* Copyright 2016-2022 DiffPlug
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -22,12 +22,20 @@
2222
import java.util.ArrayList;
2323
import java.util.List;
2424

25+
import org.junit.jupiter.api.Assertions;
2526
import org.junit.jupiter.api.Test;
2627

2728
import com.diffplug.common.base.StandardSystemProperty;
2829
import com.diffplug.spotless.generic.EndWithNewlineStep;
2930

3031
class FormatterTest {
32+
@Test
33+
void toUnix() {
34+
Assertions.assertEquals("1\n2\n3", LineEnding.toUnix("1\n2\n3"));
35+
Assertions.assertEquals("1\n2\n3", LineEnding.toUnix("1\r2\r3"));
36+
Assertions.assertEquals("1\n2\n3", LineEnding.toUnix("1\r\n2\r\n3"));
37+
}
38+
3139
// Formatter normally needs to be closed, but no resources will be leaked in this special case
3240
@Test
3341
void equality() {

0 commit comments

Comments
 (0)