Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle empty files and unknown line endings better #34

Merged
merged 1 commit into from
Sep 11, 2020
Merged
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
22 changes: 16 additions & 6 deletions src/main/java/net/revelc/code/impsort/ImpSort.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand Down Expand Up @@ -75,6 +75,16 @@ public ImpSort(final Charset sourceEncoding, final Grouper grouper, final boolea
this.lineEnding = lineEnding;
}

private static List<String> readAllLines(String str) {
List<String> result = new ArrayList<>();
try (Scanner s = new Scanner(str)) {
while (s.hasNextLine()) {
result.add(s.nextLine());
}
}
return result;
}

/**
* Parses the file denoted by this path and returns the result.
*
Expand All @@ -85,20 +95,20 @@ public ImpSort(final Charset sourceEncoding, final Grouper grouper, final boolea
public Result parseFile(final Path path) throws IOException {
byte[] buf = Files.readAllBytes(path);
if (buf.length == 0) {
throw new ImpSortException(path, Reason.EMPTY_FILE);
return Result.EMPTY_FILE;
}
String file = new String(buf, sourceEncoding);
LineEnding fileLineEnding = LineEnding.determineLineEnding(file);
if (fileLineEnding == LineEnding.UNKNOWN) {
throw new ImpSortException(path, Reason.UNKNOWN_LINE_ENDING);
}
LineEnding impLineEnding;
if (lineEnding == LineEnding.KEEP) {
if (fileLineEnding == LineEnding.UNKNOWN) {
throw new ImpSortException(path, Reason.UNKNOWN_LINE_ENDING);
}
impLineEnding = fileLineEnding;
} else {
impLineEnding = lineEnding;
}
List<String> fileLines = Arrays.asList(file.split(fileLineEnding.getChars()));
List<String> fileLines = readAllLines(file);
ParseResult<CompilationUnit> parseResult = new JavaParser().parse(file);
CompilationUnit unit = parseResult.getResult()
.orElseThrow(() -> new ImpSortException(path, Reason.UNABLE_TO_PARSE));
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/net/revelc/code/impsort/Result.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class Result {
Expand All @@ -43,6 +44,9 @@ public class Result {
private final int stop;
private final LineEnding lineEnding;

public static final Result EMPTY_FILE =
new Result(null, null, null, 0, 0, "", "", Collections.emptyList(), null);

Result(Path path, Charset sourceEncoding, List<String> fileLines, int start, int stop,
String originalSection, String newSection, Collection<Import> allImports,
LineEnding lineEnding) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ public class ImpSortException extends IOException {

public enum Reason {
// @formatter:off
EMPTY_FILE("empty file"),
UNKNOWN_LINE_ENDING("unknown line ending"),
UNABLE_TO_PARSE("unable to successfully parse the Java file"),
PARTIAL_PARSE("the Java file contained parse errors")
Expand Down
33 changes: 26 additions & 7 deletions src/test/java/net/revelc/code/impsort/LineEndingEdgeCasesTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;

Expand Down Expand Up @@ -50,27 +51,45 @@ public class LineEndingEdgeCasesTest {
public void testEmptyFile() throws IOException {
Path p = folder.newFile("EmptyFile.java").toPath();
Files.write(p, new byte[0]);
ImpSortException e = assertThrows(ImpSortException.class,
() -> new ImpSort(UTF_8, eclipseDefaults, true, true, LineEnding.AUTO).parseFile(p));
assertTrue(e.getReason() == Reason.EMPTY_FILE);
assertEquals("file: " + p + "; reason: empty file", e.getMessage());
Result actual = new ImpSort(UTF_8, eclipseDefaults, true, true, LineEnding.AUTO).parseFile(p);
assertEquals(Result.EMPTY_FILE, actual);
assertTrue(actual.getImports().isEmpty());
assertTrue(actual.isSorted());
}

/**
* Test successfully parsing file without any line ending.
* Test successfully parsing file without any line ending, but line ending config set to KEEP.
*/
@Test
public void testFileWithoutLineEnding() throws IOException {
public void testFileKeepWithoutLineEnding() throws IOException {
String s =
"import java.lang.System;public class FileWithoutNewline{public static void main(String[] args){System.out.println(\"Hello, world!\");}}";
Path p = folder.newFile("FileWithoutLineEnding.java").toPath();
Files.write(p, s.getBytes(UTF_8));
ImpSortException e = assertThrows(ImpSortException.class,
() -> new ImpSort(UTF_8, eclipseDefaults, true, true, LineEnding.AUTO).parseFile(p));
() -> new ImpSort(UTF_8, eclipseDefaults, true, true, LineEnding.KEEP).parseFile(p));
assertTrue(e.getReason() == Reason.UNKNOWN_LINE_ENDING);
assertEquals("file: " + p + "; reason: unknown line ending", e.getMessage());
}

/**
* Test successfully parsing file without any line ending, and line ending config set to AUTO.
*/
@Test
public void testFileAutoWithoutLineEnding() throws IOException {
String s =
"import java.lang.System;public class FileWithoutNewline{public static void main(String[] args){System.out.println(\"Hello, world!\");}}";
Path p = folder.newFile("FileWithoutLineEnding.java").toPath();
Files.write(p, s.getBytes(UTF_8));
Result result = new ImpSort(UTF_8, eclipseDefaults, true, true, LineEnding.AUTO).parseFile(p);
assertEquals(1, result.getImports().size());
assertEquals("java.lang.System", result.getImports().iterator().next().getImport());
assertTrue(result.getImports().iterator().next().getPrefix().isEmpty());
assertTrue(result.getImports().iterator().next().getSuffix().isEmpty());
assertFalse(result.getImports().iterator().next().isStatic());
assertFalse(result.isSorted());
}

/**
* Test when the parser partially parses the file and creates a partial result.
*/
Expand Down