Skip to content

Commit 2f3e9d2

Browse files
authored
Merge pull request #33 from gswierczynski/fix-parsing-quoted-file-with-crlf-line-endings
Fix parsing when fields are quoted and rows are terminated with CRLF; Add unit test;
2 parents 7472301 + 4a28bbe commit 2f3e9d2

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

src/commonMain/kotlin/parseCsv.kt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,15 @@ internal fun parseCsv(
4343
completeValue()
4444
BeforeValue
4545
}
46+
'\r' -> {
47+
if (nextChar() == '\n') {
48+
pos++
49+
}
50+
if (row.isNotEmpty()) {
51+
completeRow()
52+
}
53+
BeforeValue
54+
}
4655
'\n' -> {
4756
if (row.isNotEmpty()) {
4857
completeRow()

src/commonTest/kotlin/CsvTest.kt

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,39 @@ class CsvTest {
7272
println(csv.toCsvText())
7373
assertEquals(3, csv.allRows.size)
7474

75+
val columnCount = header.size
76+
assertEquals(3, columnCount)
77+
78+
val nameIndex = header.indexOf("NAME")
79+
assertEquals(0, nameIndex)
80+
81+
val codeIndex = header.indexOf("CODE")
82+
assertEquals(1, codeIndex)
83+
84+
val descriptionIndex = header.indexOf("DESCRIPTION")
85+
assertEquals(2, descriptionIndex)
86+
}
87+
88+
@Test
89+
fun parseQuotedHeaderWhenNewLineIsRN() {
90+
91+
val givenCsvString =
92+
"""
93+
"NAME","CODE","DESCRIPTION"
94+
"BURGUNDY PINK","4PK.GD-S7","Pink burgundy"
95+
"HILLS PINK","BVH.5-NAR.S8","Pink hills"
96+
""".trimIndent()
97+
.replace("\n", "\r\n")
98+
99+
val csv = CsvWithHeader.fromCsvText(givenCsvString) as CsvWithHeader
100+
val header = csv.allRows[0]
101+
102+
println(csv.toCsvText())
103+
assertEquals(3, csv.allRows.size)
104+
105+
val columnCount = header.size
106+
assertEquals(3, columnCount)
107+
75108
val nameIndex = header.indexOf("NAME")
76109
assertEquals(0, nameIndex)
77110

0 commit comments

Comments
 (0)