Skip to content

Commit

Permalink
revelcGH-30: Handle files that are empty, have an unknown newline, or…
Browse files Browse the repository at this point in the history
… can't be parsed
  • Loading branch information
dwalluck committed Sep 8, 2020
1 parent 706b2bd commit e74656a
Show file tree
Hide file tree
Showing 10 changed files with 202 additions and 8 deletions.
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,13 @@
<plugin>
<groupId>org.apache.rat</groupId>
<artifactId>apache-rat-plugin</artifactId>
<configuration>
<excludes>
<exclude>src/test/resources/EmptyFile.java</exclude>
<exclude>src/test/resources/FileWithoutNewline.java</exclude>
<exclude>src/test/resources/InvalidFile.java</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>check-licenses</id>
Expand Down
50 changes: 50 additions & 0 deletions src/main/java/net/revelc/code/impsort/EmptyFileException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.revelc.code.impsort;

import java.io.IOException;
import java.nio.file.Path;

/**
* Signals that the file denoted by this path is empty.
*
* <p>
* This exception will be thrown by the {@link ImpSort#parseFile} when it encounters an empty file.
* </p>
*/
public class EmptyFileException extends IOException {
private static final long serialVersionUID = -4202864513494828247L;

private final Path path;

/**
* Constructs a {@code EmptyFileException} with {@code null} as its error detail message and the
* specified path.
*
* @param path the path
*/
public EmptyFileException(final Path path) {
this.path = path;
}

/**
* Returns the path.
*
* @return the path
*/
public Path getPath() {
return path;
}
}
20 changes: 15 additions & 5 deletions src/main/java/net/revelc/code/impsort/ImpSort.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.comments.Comment;
import com.github.javaparser.ast.comments.JavadocComment;
import com.github.javaparser.javadoc.Javadoc;
Expand Down Expand Up @@ -73,9 +72,17 @@ public ImpSort(final Charset sourceEncoding, final Grouper grouper, final boolea
this.lineEnding = lineEnding;
}

public Result parseFile(final Path path) throws IOException {
String file = new String(Files.readAllBytes(path), sourceEncoding);
public Result parseFile(final Path path)
throws IOException, EmptyFileException, UnknownLineEndingException {
byte[] buf = Files.readAllBytes(path);
if (buf.length == 0) {
throw new EmptyFileException(path);
}
String file = new String(buf, sourceEncoding);
LineEnding fileLineEnding = LineEnding.determineLineEnding(file);
if (fileLineEnding == LineEnding.UNKNOWN) {
throw new UnknownLineEndingException(path);
}
LineEnding impLineEnding;
if (lineEnding == LineEnding.KEEP) {
impLineEnding = fileLineEnding;
Expand All @@ -84,8 +91,11 @@ public Result parseFile(final Path path) throws IOException {
}
List<String> fileLines = Arrays.asList(file.split(fileLineEnding.getChars()));
ParseResult<CompilationUnit> parseResult = new JavaParser().parse(file);
CompilationUnit unit =
parseResult.getResult().orElseThrow(() -> new IOException("Unable to parse " + path));
Optional<CompilationUnit> unitOptional = parseResult.getResult();
if (!parseResult.isSuccessful() || !unitOptional.isPresent()) {
throw new IOException("Unable to parse " + path);
}
CompilationUnit unit = unitOptional.get();
Position packagePosition =
unit.getPackageDeclaration().map(p -> p.getEnd().get()).orElse(unit.getBegin().get());
NodeList<ImportDeclaration> importDeclarations = unit.getImports();
Expand Down
7 changes: 4 additions & 3 deletions src/main/java/net/revelc/code/impsort/LineEnding.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@ public static LineEnding determineLineEnding(String fileDataString) {
int crCount = 0;
int crlfCount = 0;

for (int i = 0; i < fileDataString.length(); i++) {
char c = fileDataString.charAt(i);
final int length = fileDataString.length();
for (int i = 0; i < length; i++) {
final char c = fileDataString.charAt(i);
if (c == '\r') {
if ((i + 1) < fileDataString.length() && fileDataString.charAt(i + 1) == '\n') {
if ((i + 1) < length && fileDataString.charAt(i + 1) == '\n') {
crlfCount++;
i++;
} else {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.revelc.code.impsort;

import java.io.IOException;
import java.nio.file.Path;

/**
* Signals that the file denoted by this path has an unknown line ending.
*
* <p>
* This exception will be thrown by the {@link ImpSort#parseFile} when it encounters a file with an
* unknown line ending.
* </p>
*/
public class UnknownLineEndingException extends IOException {
private static final long serialVersionUID = 4417291768648259852L;

private final Path path;

/**
* Constructs a {@code UnknownLineEndingException} with {@code null} as its error detail message
* and the specified path.
*
* @param path the path
*/
public UnknownLineEndingException(final Path path) {
this.path = path;
}

/**
* Returns the path.
*
* @return the path
*/
public Path getPath() {
return path;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,12 @@
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.DirectoryScanner;

import net.revelc.code.impsort.EmptyFileException;
import net.revelc.code.impsort.Grouper;
import net.revelc.code.impsort.ImpSort;
import net.revelc.code.impsort.LineEnding;
import net.revelc.code.impsort.Result;
import net.revelc.code.impsort.UnknownLineEndingException;

abstract class AbstractImpSortMojo extends AbstractMojo {

Expand Down Expand Up @@ -233,6 +235,10 @@ public final void execute() throws MojoExecutionException, MojoFailureException
numProcessed.getAndIncrement();
}
processResult(path, result);
} catch (EmptyFileException e) {
getLog().warn("Skipping empty file " + e.getPath());
} catch (UnknownLineEndingException e) {
getLog().warn("Skipping file with unknown line ending " + e.getPath());
} catch (IOException e) {
fail("Error reading file " + path, e);
}
Expand Down
63 changes: 63 additions & 0 deletions src/test/java/net/revelc/code/impsort/FileTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.revelc.code.impsort;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.junit.Test;

/**
* Test class for special file cases.
*/
public class FileTest {

private static Grouper eclipseDefaults =
new Grouper("java.,javax.,org.,com.", "", false, false, true);

/**
* Test successfully parsing empty (0 byte) file.
*/
@Test(expected = EmptyFileException.class)
public void test_empty_file() throws IOException, EmptyFileException, UnknownLineEndingException {
Path p =
Paths.get(System.getProperty("user.dir"), "src", "test", "resources", "EmptyFile.java");
new ImpSort(StandardCharsets.UTF_8, eclipseDefaults, true, true, LineEnding.AUTO).parseFile(p);
}

/**
* Test successfully parsing file without any newline.
*/
@Test(expected = UnknownLineEndingException.class)
public void test_file_without_newline()
throws IOException, EmptyFileException, UnknownLineEndingException {
Path p = Paths.get(System.getProperty("user.dir"), "src", "test", "resources",
"FileWithoutNewline.java");
new ImpSort(StandardCharsets.UTF_8, eclipseDefaults, true, true, LineEnding.AUTO).parseFile(p);
}

/**
* Test successfully parsing file that can't be parsed.
*/
@Test(expected = IOException.class)
public void test_invalid_file()
throws IOException, EmptyFileException, UnknownLineEndingException {
Path p =
Paths.get(System.getProperty("user.dir"), "src", "test", "resources", "InvalidFile.java");
new ImpSort(StandardCharsets.UTF_8, eclipseDefaults, true, true, LineEnding.AUTO).parseFile(p);
}

}
Empty file.
1 change: 1 addition & 0 deletions src/test/resources/FileWithoutNewline.java
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import java.lang.System;public class FileWithoutNewline{public static void main(String[] args){System.out.println("Hello, world!");}}
5 changes: 5 additions & 0 deletions src/test/resources/InvalidFile.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
public class InvalidFile {
public static void main(String[] args) {
System.out.println("Hello, world!")
}
}

0 comments on commit e74656a

Please sign in to comment.