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

Fix CSV parsing issues in presence of trailing comma #2241

Merged
merged 1 commit into from
Dec 4, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,16 @@ public ArrayList<String> next() {
trailingComma = delimitedCellLength > 0 && buf[pos + delimitedCellLength - 1] == ',';
pos += delimitedCellLength;
delimitedCellLength = cellLength = -1;
int oldLimit = limit;
haveMoreData = pos < limit || indexAfterCompactionAndFilling(pos) < limit;
// If the CSV data ends with a trailing comma, haveMoreData will be false even though there
// is one (empty) cell remaining. The cell "appears" if a trailing carriage return is added
// to the input CSV. The following code handles this edge case by checking that we have no
// more data and if the last character in the buffer was a comma. If so, it appends the
// empty cell that would otherwise be dropped.
if (!haveMoreData && buf[oldLimit - 1] == ',') {
result.add("");
}
} while (trailingComma && haveMoreData && lookingAtCell());
return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,4 +171,23 @@ public void testToCSVRowBasic() {
String expectedCSVString = "\"field0\",\"field1\",\"field2\"";
assertEquals(expectedCSVString, CsvUtil.toCsvRow(YailList.makeList(row)));
}

public void testTrailingCommaRow() throws Exception {
String testString1 = "a,b,c,,,";
String testString2 = testString1 + "\n";
YailList list1 = CsvUtil.fromCsvRow(testString1);
YailList list2 = CsvUtil.fromCsvRow(testString2);
assertEquals(6, list1.size());
assertEquals(6, list2.size());
assertEquals(list2, list1);
}

public void testTrailingCommaTable() throws Exception {
String testString1 = "a,b,c,,,\nd,e,f,,,";
String testString2 = testString1 + "\n";
YailList list1 = CsvUtil.fromCsvTable(testString1);
YailList list2 = CsvUtil.fromCsvTable(testString2);
assertEquals(list2.getObject(0), list1.getObject(0));
assertEquals(list2.getObject(1), list1.getObject(1));
}
}