Skip to content

Commit a99f260

Browse files
committed
quote value starting with comment marker in minimal quote mode
1 parent 411d3a3 commit a99f260

2 files changed

Lines changed: 21 additions & 2 deletions

File tree

src/main/java/org/apache/commons/csv/CSVFormat.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2454,10 +2454,11 @@ private void printWithQuotes(final Object object, final CharSequence charSeq, fi
24542454
}
24552455
} else {
24562456
char c = charSeq.charAt(pos);
2457-
if (c <= Constants.COMMENT) {
2457+
if (c <= Constants.COMMENT || isCommentMarkerSet() && c == commentMarker.charValue()) {
24582458
// Some other chars at the start of a value caused the parser to fail, so for now
24592459
// encapsulate if we start in anything less than '#'. We are being conservative
2460-
// by including the default comment char too.
2460+
// by including the default comment char and any configured comment marker too,
2461+
// which the parser would otherwise read back as a comment line.
24612462
quote = true;
24622463
} else {
24632464
while (pos < len) {

src/test/java/org/apache/commons/csv/CSVPrinterTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1829,6 +1829,24 @@ void testQuoteCommaFirstChar() throws IOException {
18291829
}
18301830
}
18311831

1832+
@Test
1833+
void testQuoteCommentMarkerFirstChar() throws IOException {
1834+
final CSVFormat format = CSVFormat.DEFAULT.builder().setCommentMarker(';').get();
1835+
final StringWriter sw = new StringWriter();
1836+
final String col1 = ";comment-like";
1837+
try (CSVPrinter printer = new CSVPrinter(sw, format)) {
1838+
printer.printRecord(col1, "b");
1839+
}
1840+
assertEquals("\";comment-like\",b" + RECORD_SEPARATOR, sw.toString());
1841+
// A value starting with the comment marker must read back as data, not a dropped comment line.
1842+
try (CSVParser parser = CSVParser.parse(sw.toString(), format)) {
1843+
final List<CSVRecord> records = parser.getRecords();
1844+
assertEquals(1, records.size());
1845+
assertEquals(col1, records.get(0).get(0));
1846+
assertEquals("b", records.get(0).get(1));
1847+
}
1848+
}
1849+
18321850
@Test
18331851
void testQuoteNonNumeric() throws IOException {
18341852
final StringWriter sw = new StringWriter();

0 commit comments

Comments
 (0)